@ainyc/canonry 4.180.7 → 4.182.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -45
- package/assets/agent-workspace/skills/canonry/SKILL.md +13 -10
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +7 -6
- package/assets/assets/{AuditHistoryPanel-B1lmI7wm.js → AuditHistoryPanel-1_FHpzj-.js} +1 -1
- package/assets/assets/{BacklinksPage-Bw61uQu8.js → BacklinksPage-045za10_.js} +1 -1
- package/assets/assets/{ChartPrimitives-DG35TyhH.js → ChartPrimitives-DLEICrrL.js} +1 -1
- package/assets/assets/{HistoryPage-D8z9-NkT.js → HistoryPage-36K_6asu.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-CXX9GFj8.js → MeasurementPropertyPage-B4DJGoY6.js} +1 -1
- package/assets/assets/ProjectPage-CshC68Ne.js +9 -0
- package/assets/assets/{RunRow-DXHy16T3.js → RunRow-U2CN755e.js} +1 -1
- package/assets/assets/{RunsPage-D2aE620i.js → RunsPage-D0CtU4d-.js} +1 -1
- package/assets/assets/SettingsPage-zMWieTPK.js +1 -0
- package/assets/assets/SiteHealthSection-TpQPu_Uj.js +4 -0
- package/assets/assets/{TrafficPage-DFHWgvkU.js → TrafficPage-DfLUt-64.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-DxjyRL8Y.js → TrafficSourceDetailPage-DbjNNWSt.js} +1 -1
- package/assets/assets/extract-error-message-CWqz1QPC.js +1 -0
- package/assets/assets/index-Brb7M_6G.js +86 -0
- package/assets/assets/index-DwdK2e4e.css +1 -0
- package/assets/assets/{react-sigma_core.esm.min-DAcOZae7.js → react-sigma_core.esm.min-Drqprr9L.js} +1 -1
- package/assets/assets/{vendor-lucide-nYKv-BB7.js → vendor-lucide-XjCNFK0x.js} +1 -1
- package/assets/assets/{vendor-markdown-Bn7fRwrx.js → vendor-markdown-9tTeP8v7.js} +1 -1
- package/assets/assets/{vendor-radix-4UOaVWza.js → vendor-radix-BpmvLvpp.js} +1 -1
- package/assets/assets/{vendor-recharts-D8rt5lKn.js → vendor-recharts-FA0uySU7.js} +1 -1
- package/assets/assets/{vendor-tanstack-Dock0eH1.js → vendor-tanstack-CYBjbqVr.js} +1 -1
- package/assets/index.html +7 -7
- package/dist/{chunk-VZO6CLHY.js → chunk-BDJT7XZL.js} +169 -64
- package/dist/{chunk-RXXZ5BU5.js → chunk-DY5ZDKQW.js} +183 -1
- package/dist/{chunk-CWXPBQR5.js → chunk-FVC7PGYQ.js} +47 -5
- package/dist/{chunk-XYTSKRO3.js → chunk-I3KSOMJA.js} +2 -2
- package/dist/{chunk-WJFBNCVD.js → chunk-K45YKXE4.js} +4310 -3323
- package/dist/cli.js +323 -99
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-MEPYXRBS.js → intelligence-service-HGA553GT.js} +2 -2
- package/dist/mcp.js +3 -3
- package/package.json +7 -7
- package/assets/assets/ProjectPage-BaN_rvoV.js +0 -9
- package/assets/assets/SettingsPage-BiiFqarS.js +0 -1
- package/assets/assets/SiteHealthSection-DCH2Ejtc.js +0 -4
- package/assets/assets/extract-error-message-BdXUZQW9.js +0 -1
- package/assets/assets/index-BuEq5Rhg.css +0 -1
- package/assets/assets/index-CSictO9U.js +0 -83
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{r as l,j as e,u as Re,L as fs,h as ks,o as Et,B as Ki,C as sl,k as nl,l as al,D as rl}from"./vendor-tanstack-CYBjbqVr.js";import{M as zi,I as ze,B as A,T as de,t as il,a as ol,u as ll,C as cl,P as $n,h as dl,b as ul,c as Hs,g as Qi,d as Hi,e as he,f as K,i as te,j as yt,k as De,l as ml,m as hl,n as xl,o as Wi,p as pl,q as gl,S as Ys,r as fl,s as bl,v as zs,w as Bt,x as yl,y as Ir,z as Yi,G as qt,A as lr,D as vl,E as jl,F as Nl,H as wl,J as $r,K as Ce,L as Sl,N as Cl,O as va,Q as kl,R as Al,U as Pl,V as Rl,W as Il,X as $l,Y as Tl,Z as Ml,_ as Ll,$ as Dl,a0 as El,a1 as ql,a2 as Ol,a3 as Gl,a4 as Fl,a5 as Ji,a6 as Gs,a7 as _l,a8 as Xi,a9 as sa,aa as Ul,ab as We,ac as Bl,ad as Vl,ae as Kl,af as na,ag as zl,ah as Ql,ai as Hl,aj as en,ak as Wl,al as Yl,am as Jl,an as Zi,ao as Wa,ap as Xl,aq as eo,ar as Zl,as as cr,at as ec,au as tc,av as sc,aw as nc,ax as ac,ay as rc,az as ic,aA as Rn,aB as Js,aC as oc,aD as lc,aE as cc,aF as dc,aG as to,aH as uc,aI as mc,aJ as hc,aK as xc,aL as pc,aM as so,aN as gc,aO as fc,aP as bc,aQ as yc,aR as vc,aS as jc,aT as Nc,aU as wc,aV as Sc,aW as Cc,aX as kc,aY as Ac,aZ as Pc,a_ as Rc,a$ as Ic,b0 as $c,b1 as Tc,b2 as Mc,b3 as Lc,b4 as Dc,b5 as ps,b6 as Ec,b7 as ot,b8 as qc,b9 as Oc,ba as Gc,bb as Fc,bc as _c,bd as Uc,be as Bc,bf as Vc,bg as Kc,bh as zc,bi as Qc,bj as Hc,bk as Wc,bl as Yc,bm as Jc,bn as Xc,bo as Zc,bp as ed,bq as td,br as sd,bs as nd,bt as ad,bu as rd,bv as id,bw as od,bx as ld,by as cd,bz as dd,bA as ud,bB as md,bC as hd,bD as xd,bE as pd,bF as gd,bG as fd,bH as bd,bI as yd,bJ as vd,bK as no,bL as ja,bM as jd,bN as Tr,bO as Nd,bP as wd,bQ as Sd,bR as Cd,bS as kd,bT as Ad,bU as Pd,bV as ao,bW as Rd,bX as Id,bY as $d,bZ as Mr,b_ as Td,b$ as Md,c0 as Ld,c1 as Dd,c2 as Ed,c3 as qd,c4 as Od,c5 as Gd,c6 as Fd,c7 as _d,c8 as Ud,c9 as Bd,ca as Vd,cb as Kd,cc as zd,cd as aa,ce as Qd,cf as Na,cg as Hd,ch as Wd,ci as Yd,cj as Jd,ck as Xd,cl as Zd,cm as eu,cn as tu,co as ro,cp as su,cq as nu,cr as au,cs as ru,ct as iu,cu as ou,cv as Fn,cw as lu,cx as cu,cy as du,cz as Lr,cA as uu}from"./index-Brb7M_6G.js";import{R as mu}from"./RunRow-U2CN755e.js";import{u as Tn,D as pn,a as Xs,b as io,M as ea,c as js,S as hu}from"./SiteHealthSection-TpQPu_Uj.js";import{e as xu,q as ra,U as pu,r as gu,L as fu,s as oo,i as bu,P as ia,D as lo,t as yu,u as vu,E as ju,C as oa,v as Nu}from"./vendor-lucide-XjCNFK0x.js";import{C as la,f as tn,a as ls,b as Vt,c as Ot,d as ss,e as nt,g as as,h as Zs,M as co,i as uo,o as Cs,j as qs,p as wu}from"./ChartPrimitives-DLEICrrL.js";import{u as Su,a as Cu,b as ku,t as Au,e as Pu,c as mt}from"./extract-error-message-CWqz1QPC.js";import{R as sn,C as nn,a as ca,X as an,Y as rn,T as on,b as Ya,L as da,A as Ls,d as Ws,e as Ru}from"./vendor-recharts-FA0uySU7.js";import{A as Iu}from"./AuditHistoryPanel-1_FHpzj-.js";import{a as $u,b as Tu}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-BpmvLvpp.js";import"./vendor-markdown-9tTeP8v7.js";import"./vendor-yaml-GWJz5H2G.js";function Os(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 Mu(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let r=t;r<=s&&(a.push(r),!(a.length>=n));r=Lu(r,1));return a}function Lu(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const r=a.getUTCFullYear(),o=String(a.getUTCMonth()+1).padStart(2,"0"),i=String(a.getUTCDate()).padStart(2,"0");return`${r}-${o}-${i}`}function 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 Eu(t,s){const n=Du(t,s);return n===null?null:Math.round(n*100)}function wa(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Os(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Os(t.prior)} ${s})`:`Flat ${n} (${Os(t.prior)} ${s})`}const mo=30;function Dr(t){return Math.round(t*10)/10}function qu(t){return t.prior>=mo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Dr(t.deltaAbs)} vs ${Dr(t.prior)}`}function Ou(t,s,n){return t.prior>=mo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Os(Math.round(t.deltaAbs))} ${s} ${n}`}const Gu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function ho(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function xo(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 po(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(ho).map(xo).filter(Boolean)):new Set}function go(t,s){const n=ho(t).map(xo).filter(Boolean).filter(a=>!Gu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Fu(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function _u(t,s){const n=po(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const o of s){if(o.category!=="content"){r.push(o);continue}const i=go(Fu(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function Uu(t){const s=po(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=go(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const Bu=1e6;function Vu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/Bu)}const fo={queryClass:"all"},Ku=["all","non-brand","branded"];function zu(t){return typeof t=="string"&&Ku.includes(t)}function Qu(t){const s=zu(t.class)?t.class:fo.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 Hu(t,s){return s===null||t===null?!1:t!==s}function Wu(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===fo.queryClass?void 0:t.queryClass}}const Fs=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Er={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Yu={"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."},Ju="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Xu(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 Zu({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const r=new Map(t.perCompetitor.map(i=>[i.domain,i.mentionSnapshots])),o=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(i=>({label:i,mentions:r.get(i)??0,isYou:!1}))].sort((i,u)=>u.mentions-i.mentions||(i.label<u.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(ze,{text:Ju})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const u=i.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${i.isYou?"text-heading font-medium":"text-secondary"}`,children:i.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${i.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${u>0?Math.max(u,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[u.toFixed(1),"%"]})]},i.label)})})]})}function em({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",u=!i&&t.branded.snapshotsTotal>0,m=u?a:"non-brand",d=i?"pooled":m,p=m==="branded"?t.branded:t.breakdown,h=m==="branded"?t.breakdown:t.branded,j=Xu(p,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:h.snapshotsTotal>0}),b=d==="non-brand"?zi[t.tone]:"text-secondary";function g(f){const y=Fs.findIndex(z=>z.value===m);let C=null;f.key==="ArrowRight"||f.key==="ArrowDown"?C=(y+1)%Fs.length:f.key==="ArrowLeft"||f.key==="ArrowUp"?C=(y-1+Fs.length)%Fs.length:f.key==="Home"?C=0:f.key==="End"&&(C=Fs.length-1),C!==null&&(f.preventDefault(),r(Fs[C].value),f.currentTarget.querySelectorAll('[role="radio"]')[C]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:o,className:"mention-share-label-text",children:"Mention share"}),e.jsx(ze,{text:Yu[d]})]}),u?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:g,children:Fs.map(f=>{const y=f.value===m;return e.jsx("button",{type:"button",role:"radio","aria-checked":y,tabIndex:y?0:-1,onClick:()=>r(f.value),className:`segmented-option min-h-11 ${y?"segmented-option-active":""}`,children:f.label},f.value)})}):e.jsx("span",{className:"mention-share-class",children:Er[d]})]}),j.numeric?e.jsxs("p",{className:`mention-share-value ${b}`,children:[j.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:j.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Er[d]}),` · ${j.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),j.showRows&&e.jsx(Zu,{breakdown:p,projectLabel:s,competitorDomains:n})]})}const _s=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],qr=5;function tm(t){switch(t){case"non-brand":return"Counts queries that do not name your brand.";case"branded":return"Counts queries that name your brand.";default:return"Counts every tracked query, so share of voice is not shown."}}function sm(t){return t===null?"Not measured":`${t.toFixed(1)}%`}function bo(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function nm({value:t,onChange:s}){function n(a){const r=_s.findIndex(u=>u.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%_s.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+_s.length)%_s.length:a.key==="Home"?o=0:a.key==="End"&&(o=_s.length-1),o===null)return;a.preventDefault();const i=_s[o];s(i.value),a.currentTarget.querySelectorAll('[role="radio"]')[o].focus()}return e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"block text-sm font-medium text-heading",children:"History"}),e.jsx("div",{role:"radiogroup","aria-label":"Competitor history window",className:"segmented",onKeyDown:n,children:_s.map(a=>{const r=a.value===t;return e.jsx("button",{type:"button",role:"radio","aria-checked":r,tabIndex:r?0:-1,onClick:()=>s(a.value),className:`segmented-option min-h-11 ${r?"segmented-option-active":""}`,children:a.label},a.value)})})]})}function Ja({row:t,isProject:s=!1,metricsAvailable:n=!0,canManage:a,onPin:r,onUnpin:o}){const i=!s&&a&&!t.pinned&&!!r,u=!s&&a&&t.pinned&&!!o,m=n&&t.sampleUrls.length>0,[d,p]=l.useState(!1),[h,j]=l.useState(null);async function b(g,f){if(!(!f||d)){p(!0),j(null);try{await f(t.domain)===!1&&j(`Could not ${g} competitor. Try again.`)}catch{j(`Could not ${g} competitor. Try again.`)}finally{p(!1)}}}return e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"font-medium text-heading",children:[t.label,s?e.jsx("span",{className:"ml-1 text-secondary",children:"(you)"}):null]}),e.jsx("td",{className:"text-secondary",children:s?"Your brand":bo(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:n?sm(t.shareOfVoice):"Unavailable"}),e.jsx("td",{className:"tabular-nums text-secondary",children:n?t.mentionCount:"Unavailable"}),e.jsx("td",{className:"tabular-nums text-secondary",children:n?t.citationCount:"Unavailable"}),e.jsx("td",{className:"text-right",children:i||u||m?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[m?e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.sampleUrls.map(g=>e.jsx("li",{className:"break-all",children:g},g))})]}):null,u&&o?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:d,onClick:()=>{b("unpin",o)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,i&&r?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:d,onClick:()=>{b("pin",r)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,h?e.jsx("span",{role:"alert",className:"sr-only",children:h}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function Xa({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function am({rows:t,canManage:s,onPin:n}){const[a,r]=l.useState(!1),o=a?t:t.slice(0,qr);return e.jsxs("tbody",{children:[e.jsx(Xa,{children:"Observed in this window"}),o.length>0?o.map(i=>e.jsx(Ja,{row:{...i,pinned:!1},canManage:s,onPin:n},i.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No direct competitors were observed in this window."})}),t.length>qr?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-sm text-secondary",children:["Showing ",o.length," of ",t.length," observed competitors."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":a,"aria-label":a?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>r(i=>!i),children:a?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function rm({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,u]=l.useState(null);async function m(){const d=n.trim();if(!(!d||r)){o(!0),u(null);try{if(await t(d)===!1){u("Could not add competitor. Try again.");return}a("")}catch{u("Could not add competitor. Try again.")}finally{o(!1)}}}return e.jsxs("details",{className:"inline-disclosure competitor-landscape-manage",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:d=>{d.preventDefault(),m()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:d=>a(d.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(A,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Or({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:u,onAddCompetitor:m,error:d,onRetry:p,isLoading:h=!1,scopeLabel:j}){const b=a&&!r,g=s?.pinned??n,f=s?.observed??[],y=s?.otherSources??[],C=s?.evidence,z=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":h,className:"competitor-landscape",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{id:"competitor-landscape-title",children:"Competitor landscape"}),j?e.jsx("p",{className:"supporting-copy mt-1",children:j}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:tm(s.filters?.queryClass)}):null]}),e.jsx(nm,{value:t,onChange:o})]}),d?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:d}),p?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:p,children:"Retry competitor history"}):null]}):null,h&&!s&&g.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-48 animate-pulse rounded-md bg-surface-subtle",children:e.jsx("span",{className:"sr-only",children:"Loading competitor history"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table","aria-label":"Competitor landscape",children:[e.jsx("caption",{className:"sr-only",children:"Pinned competitors followed by competitors observed in the selected history window."}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Share of voice"}),e.jsx("th",{scope:"col",children:"Mentions"}),e.jsx("th",{scope:"col",children:"Citations"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[s?e.jsxs(e.Fragment,{children:[e.jsx(Xa,{children:"You"}),e.jsx(Ja,{row:s.project,isProject:!0,canManage:!1})]}):null,e.jsx(Xa,{children:"Pinned"}),g.length>0?g.map(L=>e.jsx(Ja,{row:{...L,pinned:!0},metricsAvailable:!!s,canManage:b,onUnpin:u},L.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s?e.jsx(am,{rows:f,canManage:b,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),C?e.jsxs("p",{className:"text-sm text-secondary",children:[C.answeredResults," answer results and ",C.sourceResults," source results in this window.",C.missingAnswerTextResults>0?` ${C.missingAnswerTextResults} result${C.missingAnswerTextResults===1?"":"s"} without answer text excluded from mention share.`:"",C.incompleteSourceResults>0?` ${C.incompleteSourceResults} incomplete source result${C.incompleteSourceResults===1?"":"s"} excluded from negative citation evidence.`:"",C.excludedProbeResults>0||C.excludedNonCompletedResults>0?` ${C.excludedProbeResults+C.excludedNonCompletedResults} probe or incomplete run${C.excludedProbeResults+C.excludedNonCompletedResults===1?"":"s"} excluded.`:""]}):null,s?.truncated?e.jsx("p",{className:"text-sm text-secondary",children:"Results are limited to the top 100 observed competitors and other sources. Pinned competitors are complete."}):null,z>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${z} competitor${z===1?" is":"s are"} pending publication across markets.`:`${z} competitor${z===1?" is":"s are"} pending publication for this market.`}):null,y.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",y.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:y.map(L=>e.jsxs("li",{children:[e.jsxs("span",{children:[L.label," · ",bo(L.surfaceClass)," · ",L.citationCount," citations"]}),L.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:L.sampleUrls.map(R=>e.jsx("li",{className:"break-all",children:R},R))}):null]},L.domain))})]}):null]}),b&&m?e.jsx(rm,{onAddCompetitor:m}):null]})}function Gr({state:t,label:s}){return e.jsx(de,{tone:ol(t),children:s??il(t)})}function Fr({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},o=n.length-1,i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=n.map((d,p)=>{const h=new Date(d.createdAt).toLocaleDateString();return`${p===o?"Latest run, ":""}${h}: ${d.citationState}${d.model?`, model ${d.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${m}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((d,p)=>{const h=!!(d.model&&p>0&&n[p-1]?.model&&n[p-1].model!==d.model),j=p===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[d.citationState]??"rounded-sm"} ${a[d.citationState]??"bg-mono-700"} ${h?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${j?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[d.citationState,new Date(d.createdAt).toLocaleDateString(),d.model?`model ${d.model}`:null,h?"model changed":null,j?"latest run":null].filter(Boolean).join(" · ")},`${d.runId}:${d.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Za(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const o=s.get(r.createdAt);o?o.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:o}])=>({runId:o,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const im=320;function om(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function lm(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function _r(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 Ur(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 Br(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,o=t[t.length-2].citationState;if(o!=="cited"&&r==="cited")return`Newly ${n}`;if(o==="cited"&&r!=="cited")return"Lost since last run";let i=0;for(let u=t.length-1;u>=0&&t[u].citationState===r;u--)i++;return r==="cited"?i<=1?`${a} in latest run`:`${a} for ${i} runs`:i<=1?`Not ${n} in latest run`:`Not ${n} across ${i} runs`}function cm(t,s){return t.map(n=>yo(n,s))}function yo(t,s){return s==="citations"?t:{...t,citationState:_r(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:_r(n,s)}))}}function Vr(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,o=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",u=o==="cited"||o==="emerging";return r==="lost"||o!==null&&u&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!u&&i?{key:s,label:`New ${n}`,tone:"positive"}:o===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function dm(t){const s=Za(cm(t,"mentions")),n=Za(t);return[Vr(s,"mentions"),Vr(n,"citations")]}function um({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 Kr({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:dm(t).map(s=>e.jsx(um,{signal:s},s.key))})}function mm({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=ll(),[r,o]=l.useState(new Set),[i,u]=l.useState("mentions"),[m,d]=l.useState(n),[p,h]=l.useState("all"),j=l.useMemo(()=>{const c=new Map;for(const v of t){const S=v.query,D=v.queryClass??null,T=s?v.location??null:null,N=JSON.stringify([S,D,T]),U=c.get(N)??{key:N,phrase:S,queryClass:D,location:T,items:[],rawItems:[]};U.items.push(yo(v,i)),U.rawItems.push(v),c.set(N,U)}return[...c.values()]},[t,i,s]),b=l.useMemo(()=>j.filter(c=>p==="all"||(p==="unclassified"?c.queryClass===null:c.queryClass===p)),[j,p]),g=Tn({rows:b,getSearchText:lm}),f=g.rows.map(c=>c.key),y=f.length>0&&f.every(c=>r.has(c)),C=c=>{o(v=>{const S=new Set(v);return S.has(c)?S.delete(c):S.add(c),S})},z=i==="mentions"?"mentioned":"cited",L=i==="mentions"?"Mention History":"Citation History",R=i==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":i==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:i==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{o(c=>{const v=new Set(c);for(const S of f)y?v.delete(S):v.add(S);return v})},children:y?"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":m==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>d("detailed"),children:"Detailed"})]})]})]})]}),j.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(pn,{value:g.query,onChange:g.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"w-full max-w-md"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-secondary",children:["Query class",e.jsxs("select",{value:p,onChange:c=>{h(c.target.value),g.setPage(1)},className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:L}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:g.rows.map(({key:c,phrase:v,queryClass:S,location:D,items:T,rawItems:N})=>{const U=r.has(c),E=T.map(_=>_.citationState),B=E.includes("cited")?"cited":E.includes("emerging")?"emerging":E.includes("lost")?"lost":E.every(_=>_==="pending")?"pending":"not-cited",H=Za(T),ge=T.filter(_=>_.citationState===cl.cited||_.citationState==="emerging").length,ke=Br(H,i);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>C(c),onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),C(c))},tabIndex:0,role:"button","aria-expanded":U,children:[e.jsx("td",{children:e.jsx(xu,{size:14,className:`transition-transform duration-150 text-muted ${U?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:v}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:D??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(de,{tone:"neutral",className:"whitespace-nowrap",children:om(S)}),T.map(_=>e.jsx($n,{provider:_.provider},_.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{state:B,label:Ur(B,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${ge} of ${T.length} engines ${R}`,children:[ge,"/",T.length]})]})}),e.jsx("td",{children:e.jsx(Fr,{history:H})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ke}),e.jsx(Kr,{items:N})]}),e.jsx("td",{})]}),U&&T.map((_,se)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx($n,{provider:_.provider})}),e.jsx("td",{children:e.jsx(Gr,{state:_.citationState,label:Ur(_.citationState,i)})}),e.jsx("td",{children:e.jsx(Fr,{history:_.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Br(_.runHistory,i)}),e.jsx(Kr,{items:[N[se]??_]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:re=>{re.stopPropagation(),a(_.id)},children:"View"})})]}),m==="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(pm,{item:_,onViewFull:()=>a(_.id)})})]})]},_.id))]},c)})})]})}),g.totalRows===0&&(g.hasQuery||p!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Xs,{page:g.page,pageSize:g.pageSize,visibleRows:g.rows.length,totalRows:g.totalRows,onPageChange:g.setPage,itemLabel:g.hasQuery||p!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",z==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function hm(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=ul(r);return o.length>=4?[o]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function zr(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function xm(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 pm({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:r}=xm(t.answerSnippet,im),o=hm(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:dl(a,o)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(i=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${zr(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,zr(t,i)?" · competitor source":""]},`c-${i}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(i=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:i},`co-${i}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:i=>{i.stopPropagation(),s()},children:"View full answer →"})]})}function _n({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}function pa({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:o=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:o,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>n(i),children:r?r(i):i},i))})}const Sa=nt[0],Ca=nt[1],Qr=nt[2],Hr=nt[3],gm=["both","server","ga4"],Wr={fontSize:11,paddingTop:6},Yr=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Jr=t=>typeof t=="number"?Os(Math.round(t)):String(t),Xt=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function ka(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,o)=>o<t.startIndex||o>t.endIndex?null:t.start+(o-t.startIndex)*a)}function Aa({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(ze,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function fm(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,u=o??-1;return!(t[u]!=null&&t[u-1]==null&&t[u+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function bm({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,u]=l.useState("both"),m=Su(t,{sinceMinutes:s,granularity:"day",limit:1}),d=Cu(t),h=Re({...Qi({client:K,path:{name:t}}),enabled:!!t,staleTime:Hs}).data?.connected===!0,j=Re({...Hi({client:K,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&h,staleTime:Hs}),b=l.useMemo(()=>m.data?.series?.points??[],[m.data]),g=l.useMemo(()=>{const D=j.data;return new Map((D?.days??[]).map(T=>[T.date,T.sessions]))},[j.data]),f=l.useMemo(()=>{const D=N=>N.measured!==!1;if(b.length===0||D(b[0]))return null;const T=b.findIndex(D)-1;return T<0?{from:b[0].bucket,to:b[b.length-1].bucket}:{from:b[0].bucket,to:b[T].bucket}},[b]),y=m.data?.series?.coverageStart??null,C=m.data?.series?.trends,z=l.useMemo(()=>{const D=ka(C?.crawlerContentHits,b.length),T=ka(C?.aiUserFetchHits,b.length),N=ka(C?.aiReferralLandedHits,b.length);return b.map((U,E)=>({...U,crawlerContentHits:U.measured!==!1?Xt(U.crawlerContentHits):null,aiUserFetchHits:U.measured!==!1?Xt(U.aiUserFetchHits):null,aiReferralLandedHits:U.measured!==!1?Xt(U.aiReferralLandedHits):null,ga4Visits:g.get(U.bucket)??null,crawlTrend:D[E],fetchTrend:T[E],visitTrend:N[E]}))},[b,g,C]),L=m.data?.totals,R=L&&{crawlers:Xt(L.crawlerContentHits),fetches:Xt(L.aiUserFetchHits),visits:Xt(L.aiReferralLandedHits)},c=l.useMemo(()=>b.reduce((D,T)=>({crawlers:D.crawlers+Xt(T.crawlerContentHits),fetches:D.fetches+Xt(T.aiUserFetchHits),visits:D.visits+Xt(T.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[b]),v=R??c,S=v.crawlers>0||v.fetches>0||v.visits>0;if(m.isLoading)return e.jsx(he,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(m.isError)return e.jsxs(he,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!S){const D=d.data?.sources,T=D!==void 0&&D.length===0,N=!T&&y===null;return e.jsxs(he,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:T?"No server-side traffic source connected yet.":N?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:T?"Connect a traffic source to see how AI engines read this site over time.":N?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(he,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Aa,{label:"AI crawlers",value:Os(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Aa,{label:"AI page fetches",value:Os(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Aa,{label:"AI visitors",value:Os(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),b.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:Xt(b[b.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:Xt(b[b.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:Xt(b[b.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:g.get(b[b.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(ze,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:D=>a(D.target.checked),className:"accent-current"}),"Page fetches"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:D=>o(D.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(sn,{width:"100%",height:206,children:e.jsxs(nn,{data:z,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ca,{stroke:la,vertical:!1}),e.jsx(an,{dataKey:"bucket",tick:Vt,stroke:ls,tickFormatter:tn,minTickGap:28}),e.jsx(rn,{tick:Vt,stroke:ls,width:48,allowDecimals:!1}),e.jsx(on,{contentStyle:ss.contentStyle,labelStyle:ss.labelStyle,itemStyle:ss.itemStyle,labelFormatter:Ot,formatter:Jr}),f&&e.jsx(Ya,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(da,{wrapperStyle:Wr,iconType:"plainline",iconSize:14,formatter:D=>Yr.has(D)?"":D}),e.jsx(Ls,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Sa,fill:Sa,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Ls,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ca,fill:Ca,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ws,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Sa,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ws,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ca,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(ze,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(pa,{windows:gm,value:i,onChange:u,label:"Visit measurement source",formatOption:D=>D==="ga4"?"GA4":D==="both"?"Both":"Server"})]}),e.jsx(sn,{width:"100%",height:176,children:e.jsxs(nn,{data:z,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(ca,{stroke:la,vertical:!1}),e.jsx(an,{dataKey:"bucket",tick:Vt,stroke:ls,tickFormatter:tn,minTickGap:28}),e.jsx(rn,{tick:Vt,stroke:ls,width:48,allowDecimals:!1}),e.jsx(on,{contentStyle:ss.contentStyle,labelStyle:ss.labelStyle,itemStyle:ss.itemStyle,labelFormatter:Ot,formatter:Jr}),f&&e.jsx(Ya,{x1:f.from,x2:f.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(da,{wrapperStyle:Wr,iconType:"plainline",iconSize:14,formatter:D=>Yr.has(D)?"":D}),i!=="ga4"&&e.jsx(Ws,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Qr,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ws,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Hr,strokeWidth:1.8,strokeDasharray:"5 3",dot:fm(z.map(D=>D.ga4Visits),Hr)}),r&&i!=="ga4"&&e.jsx(Ws,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Qr,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const ym=6,bn="__other__",gn="_socialTotal";function vm(t,s=ym){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,h)=>h[1]!==p[1]?h[1]-p[1]:p[0].localeCompare(h[0])),r=a.slice(0,s),o=new Set(r.map(([p])=>p)),i=Math.max(0,a.length-s),u=new Map;for(const p of t){let h=u.get(p.date);h||(h={date:p.date,[gn]:0},u.set(p.date,h));const j=o.has(p.source)?p.source:bn;h[j]=(h[j]??0)+p.sessions,h[gn]=(h[gn]??0)+p.sessions}const m=[...u.values()].sort((p,h)=>String(p.date).localeCompare(String(h.date))),d=r.map(([p])=>p);return i>0&&d.push(bn),{data:m,sources:d,otherCount:i}}function fn(t){return t.replace(/\+/g," ")}function vo(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Xr="_totalSessions",Zr="_organicSessions";function jm(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Xr]:i.sessions,[Zr]:i.organicSessions});for(const i of t.days){let u=n.get(i.date);u||(u={[Xr]:0,[Zr]:0},n.set(i.date,u));for(const m of i.bySource)u[m.source]=(u[m.source]??0)+m.sessions}const a=[...n.entries()].sort(([i],[u])=>i.localeCompare(u)).map(([i,u])=>({date:i,...u})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const Nm=["7d","30d","90d"],wm={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ms=nt,er=as.textDim,jo=as.textFaint,Nn=25;function Sm(t){return io(t.landingPage)}const Cm=25,km=10,Pa={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Un(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function No(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Am({projectName:t}){const{data:s,isLoading:n,isError:a}=ku(t);if(n)return e.jsx(he,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(he,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!te()&&e.jsx(fs,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(he,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!te()&&e.jsxs(e.Fragment,{children:[e.jsx(fs,{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(he,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:o.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(de,{tone:Au(o.status),children:o.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:o.lastSyncedAt?No(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:te()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(fs,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function Pm({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Am,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(pa,{windows:Nm,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Rm,{projectName:t,window:s}),e.jsx(bm,{projectName:t,sinceMinutes:wm[s]})]})}function Rm({projectName:t,window:s}){const n=ks(),a=s??"30d",[r,o]=l.useState(null),[i,u]=l.useState(null),[m,d]=l.useState(!0),[p,h]=l.useState(!1),[j,b]=l.useState(!1),[g,f]=l.useState(null),[y,C]=l.useState(null),[z,L]=l.useState("sessions"),[R,c]=l.useState("desc"),[v,S]=l.useState("sessions"),[D,T]=l.useState("desc"),[N,U]=l.useState("sessions"),[E,B]=l.useState("desc"),[H,ge]=l.useState("sessions"),[ke,_]=l.useState("desc"),[se,re]=l.useState(Pa),[X,Q]=l.useState([]),[P,G]=l.useState([]),[Y,J]=l.useState(!1);async function W(O){d(!0),f(null);try{const Se=await n.fetchQuery({...Qi({client:K,path:{name:t}}),staleTime:Hs});if(O.current)return;if(o(Se),!Se.connected){u(null),re(Pa),Q([]),G([]),d(!1);return}const be=a==="all"?void 0:a,ve=await n.fetchQuery({...ml({client:K,path:{name:t},query:be?{window:be}:void 0}),staleTime:Hs}).then(rs=>rs),ft=ve.windowStart||ve.windowEnd?{...ve.windowStart?{startDate:ve.windowStart}:{},...ve.windowEnd?{endDate:ve.windowEnd}:{}}:void 0,[Je,At,Nt]=await Promise.all([n.fetchQuery({...Hi({client:K,path:{name:t},query:be?{window:be}:void 0}),staleTime:Hs}).catch(()=>Pa),n.fetchQuery({...hl({client:K,path:{name:t},query:be?{window:be}:void 0}),staleTime:Hs}).catch(()=>[]),n.fetchQuery({...xl({client:K,path:{name:t},query:ft}),staleTime:Hs}).catch(()=>[])]);if(O.current)return;u(ve),re(Je),Q(At),G(Nt),d(!1)}catch(Se){if(O.current)return;f(Se instanceof Error?Se.message:"Failed to load GA4 data"),d(!1)}}l.useEffect(()=>{const O={current:!1};return W(O),()=>{O.current=!0}},[t,a,n]);async function xe(){h(!0),f(null),C(null);try{const O=await Wi(t);C(`Synced ${O.rowCount.toLocaleString()} page rows, ${O.aiReferralCount.toLocaleString()} AI and ${O.socialReferralCount.toLocaleString()} social referral rows (${O.days} days)`),await yt(n,"ga"),await W({current:!1})}catch(O){f(O instanceof Error?O.message:"Sync failed")}finally{h(!1)}}async function V(){b(!0),f(null),C(null);try{await pl(t),await yt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),u(null),C("GA4 disconnected")}catch(O){f(O instanceof Error?O.message:"Disconnect failed")}finally{b(!1)}}function le(O){Ae.setPage(1),z===O?c(Se=>Se==="desc"?"asc":"desc"):(L(O),c("desc"))}function je(O){v===O?T(Se=>Se==="desc"?"asc":"desc"):(S(O),T("desc"))}function Fe(O){N===O?B(Se=>Se==="desc"?"asc":"desc"):(U(O),B("desc"))}const Le=l.useMemo(()=>i?.topPages?[...i.topPages].sort((O,Se)=>{const be=O[z],ve=Se[z];return typeof be=="string"&&typeof ve=="string"?R==="asc"?be.localeCompare(ve):ve.localeCompare(be):R==="asc"?be-ve:ve-be}):[],[i?.topPages,z,R]),Ae=Tn({rows:Le,getSearchText:O=>io(O.landingPage),pageSize:km}),Xe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((O,Se)=>{const be=O[v],ve=Se[v];return typeof be=="string"&&typeof ve=="string"?D==="asc"?be.localeCompare(ve):ve.localeCompare(be):D==="asc"?be-ve:ve-be}):[],[i?.aiReferrals,v,D]),lt=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((O,Se)=>{const be=O[H],ve=Se[H];return typeof be=="string"&&typeof ve=="string"?ke==="asc"?be.localeCompare(ve):ve.localeCompare(be):ke==="asc"?be-ve:ve-be}):[],[i?.aiReferralLandingPages,H,ke]),we=Tn({rows:lt,getSearchText:Sm,pageSize:Cm}),et=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 Ve(O){we.setPage(1),H===O?_(Se=>Se==="desc"?"asc":"desc"):(ge(O),_("desc"))}const _e=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((O,Se)=>{const be=O[N],ve=Se[N];return typeof be=="string"&&typeof ve=="string"?E==="asc"?be.localeCompare(ve):ve.localeCompare(be):E==="asc"?be-ve:ve-be}):[],[i?.socialReferrals,N,E]),{socialChartData:Ue,socialChartSources:Ie,socialOtherCount:F}=l.useMemo(()=>{const O=vm(P);return{socialChartData:O.data,socialChartSources:O.sources,socialOtherCount:O.otherCount}},[P]),{chartData:$,chartSources:q,dateRange:me}=l.useMemo(()=>{const O=jm(se,X);return{chartData:O.data,chartSources:O.sources,dateRange:O.dateRange}},[se,X]);if(m&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return te()?e.jsx(he,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Im,{projectName:t,onConnected:()=>{(async()=>(await yt(n,"ga"),await W({current:!1})))()}});const fe=i?.organicSharePctDisplay??"0%",Z=i?.channelBreakdown?.organic.sharePctDisplay??fe,Ze=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,Kt=i?.aiSessionsDeduped??0,Ye=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,$e=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Te=i?.paidAiSessionsBySession??0,pt=i?.paidAiSharePctBySessionDisplay??"0%",ct=i?new Set(i.aiReferrals.map(O=>O.source.toLowerCase())).size:0,Oe=Xe[0]??null,Qe=i?.totalDirectSessions??0,vt=i?.directSharePctDisplay??"0%",Ke=i?.channelBreakdown?.direct.sessions??Qe,Ee=i?.channelBreakdown?.direct.sharePctDisplay??vt,qe=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,jt=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ge=i?.socialSessions??0,It=i?.socialSharePctDisplay??"0%",Gt=i?.channelBreakdown?.social.sessions??Ge,gt=i?.channelBreakdown?.social.sharePctDisplay??It,kt=i?new Set(i.socialReferrals.map(O=>O.source.toLowerCase())).size:0,ht=_e[0]??null;return e.jsxs(e.Fragment,{children:[g&&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:g}),y&&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:y}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!te()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:p,onClick:De(xe),children:[e.jsx(ra,{className:`w-3.5 h-3.5 mr-1.5 ${p?"animate-spin":""}`}),p?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:j,onClick:De(V),children:[e.jsx(pu,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(ze,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ra,{value:Un(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ra,{value:Un(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${fe} of total`,tone:"positive"}),e.jsx(Ra,{value:i.totalUsers===null?"—":Un(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!te()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:p,onClick:De(xe),children:[e.jsx(ra,{className:`w-3.5 h-3.5 mr-1.5 ${p?"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(ze,{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."})]})]}),me&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(me.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(me.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),$.length>0&&e.jsxs(he,{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:q.length>0?"AI vs. total sessions":"All sessions (baseline)"}),q.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),q.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:$,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(an,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:tn}),e.jsx(rn,{tick:Vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...ss,labelFormatter:Ot,formatter:(O,Se)=>{const be=typeof O=="number"?O.toLocaleString():String(O??0),ve=String(Se??"");return ve==="_totalSessions"?[be,"Total Sessions"]:ve==="_organicSessions"?[be,"Organic Sessions"]:[be,ve]}}),e.jsx(da,{wrapperStyle:{fontSize:11,color:as.text},formatter:O=>O==="_totalSessions"?"Total Sessions":O==="_organicSessions"?"Organic Sessions":O}),e.jsx(Ls,{type:"monotone",dataKey:"_totalSessions",stroke:as.textFaint,fill:as.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),q.map((O,Se)=>e.jsx(Ls,{type:"monotone",dataKey:O,stackId:"ai",stroke:Ms[Se%Ms.length],fill:Ms[Se%Ms.length],fillOpacity:.4,strokeWidth:1.5},O))]})})})]}),e.jsxs(he,{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(os,{label:"Organic",value:Z,hint:`${Ze.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(os,{label:"Social",value:gt,hint:`${Gt.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(os,{label:"Direct",value:Ee,hint:`${Ke.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(os,{label:"Visitors from AI (at least)",value:$e,hint:Te>0?`${Ye.toLocaleString()} sessions · ${Te.toLocaleString()} paid`:`${Ye.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(os,{label:"Other channels",value:jt,hint:`${qe.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."})]}),Oe&&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:Oe.source})," via ",Oe.medium,", accounting for ",Oe.sessions.toLocaleString()," sessions.",Te>0&&e.jsxs("span",{children:[" Paid AI: ",Te.toLocaleString()," sessions (",pt,")."]})]})]}),e.jsxs(he,{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?`${ct} 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(Zt,{label:"Source",sortKey:"source",current:v,dir:D,onSort:je,align:"left"}),e.jsx(Zt,{label:"Medium",sortKey:"medium",current:v,dir:D,onSort:je,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(Zt,{label:"Sessions",sortKey:"sessions",current:v,dir:D,onSort:je,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Xe.map(O=>e.jsx(Tm,{referral:O,totalSessions:Kt},`${O.source}:${O.medium}:${O.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(he,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:et})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(pn,{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(Zt,{label:"Landing Page",sortKey:"landingPage",current:H,dir:ke,onSort:Ve,align:"left"}),e.jsx(Zt,{label:"Source",sortKey:"source",current:H,dir:ke,onSort:Ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Zt,{label:"Sessions",sortKey:"sessions",current:H,dir:ke,onSort:Ve,align:"right"})]})}),e.jsx("tbody",{children:we.rows.map(O=>e.jsx(Mm,{row:O},`${O.landingPage}:${O.source}:${O.medium}:${O.sourceDimension}`))})]})}),e.jsx(Xs,{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(ze,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(he,{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(os,{label:"Social Sessions",value:Un(Ge),hint:`${Ge.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(os,{label:"Share of Traffic",value:It,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(os,{label:"Platforms",value:String(kt),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."})]}),ht&&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:`${ht.source} via ${ht.medium}`,children:vo(fn(ht.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:ht.medium,children:["via ",fn(ht.medium)," · ",ht.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(os,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(os,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(os,{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."})]})]})]}),Ue.length>0&&e.jsxs(he,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),F>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ie.length-1," sources · ",F," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:Ue,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(an,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:tn}),e.jsx(rn,{tick:Vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...ss,labelFormatter:Ot,formatter:(O,Se)=>{const be=typeof O=="number"?O.toLocaleString():String(O??0),ve=String(Se??"");if(ve===gn)return[be,"Total Social"];if(ve===bn){const ft=`Other (${F} source${F===1?"":"s"})`;return[be,ft]}return[be,fn(ve)]}}),e.jsx(Ls,{type:"monotone",dataKey:gn,stroke:jo,fill:as.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ie.map((O,Se)=>{const ve=O===bn?er:Ms[Se%Ms.length];return e.jsx(Ls,{type:"monotone",dataKey:O,stackId:"social",stroke:ve,fill:ve,fillOpacity:.4,strokeWidth:1.5},O)})]})})}),e.jsx(Dm,{sources:Ie,otherCount:F})]}),e.jsxs(he,{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?_e.length>Nn&&!Y?`Top ${Nn} of ${_e.length}`:`${_e.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(Zt,{label:"Source",sortKey:"source",current:N,dir:E,onSort:Fe,align:"left"}),e.jsx(Zt,{label:"Medium",sortKey:"medium",current:N,dir:E,onSort:Fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Zt,{label:"Sessions",sortKey:"sessions",current:N,dir:E,onSort:Fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(Y?_e:_e.slice(0,Nn)).map(O=>e.jsx(Lm,{referral:O,totalSessions:Ge},`${O.source}:${O.medium}:${O.channelGroup}`))})]})}),_e.length>Nn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>J(O=>!O),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:Y?`Show top ${Nn}`:`Show all ${_e.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(ze,{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(pn,{value:Ae.query,onChange:Ae.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(Zt,{label:"Landing Page",sortKey:"landingPage",current:z,dir:R,onSort:le,align:"left"}),e.jsx(Zt,{label:"Sessions",sortKey:"sessions",current:z,dir:R,onSort:le,align:"right"}),e.jsx(Zt,{label:"Organic",sortKey:"organicSessions",current:z,dir:R,onSort:le,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Ae.rows.map(O=>e.jsx($m,{page:O},O.landingPage))})]})}),Ae.totalRows===0&&Ae.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Xs,{page:Ae.page,pageSize:Ae.pageSize,visibleRows:Ae.rows.length,totalRows:Ae.totalRows,onPageChange:Ae.setPage,itemLabel:Ae.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 ${No(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Im({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,u]=l.useState(null),[m,d]=l.useState(!1),[p,h]=l.useState(null),j=l.useRef(null),b=l.useCallback(f=>{const y=f.target.files?.[0];if(!y)return;h(null),o(y.name);const C=new FileReader;C.onload=()=>{const z=C.result;try{const L=JSON.parse(z);if(!L.client_email||!L.private_key){h("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),u(null);return}u(z)}catch{h("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},C.onerror=()=>{h("Failed to read file."),u(null)},C.readAsText(y)},[]);async function g(){if(h(null),!n.trim()){h("Property ID is required.");return}if(!i){h("Please upload a service account key file.");return}d(!0);try{await gl(t,{propertyId:n.trim(),keyJson:i});try{await Wi(t)}catch{}s()}catch(f){h(f instanceof Error?f.message:"Failed to connect GA4")}finally{d(!1)}}return e.jsxs(he,{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:f=>a(f.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:j,type:"file",accept:".json,application/json",onChange:b,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>j.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(gu,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(A,{variant:"default",size:"sm",disabled:m||!n.trim()||!i,onClick:De(g),children:m?"Connecting & syncing…":"Connect GA4"})]})}function Zt({label:t,sortKey:s,current:n,dir:a,onSort:r,align:o}){const i=n===s;return e.jsx("th",{className:`py-1 ${o==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${i?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,i&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const wo={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Ra({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${wo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function os({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(ze,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${wo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function $m({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 So={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Co={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 Tm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=So[t.sourceDimension]??t.sourceDimension,r=Co[t.sourceDimension]??"",o=t.trafficClass==="paid"?"Paid":"Organic",i=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:i,children:o})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Mm({row:t}){const s=So[t.sourceDimension]??t.sourceDimension,n=Co[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(ea,{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 Lm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=fn(t.source),o=fn(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:o}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Dm({sources:t,otherCount:s}){const n=[{key:gn,color:jo,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===bn)n.push({key:bn,color:er,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=fn(r);n.push({key:r,color:Ms[a%Ms.length]??er,label:vo(o,32),tooltip:o})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Em(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 qm=["7d","30d","90d","all"],Bn=500,ei=[{key:"clicks",label:"Clicks",color:nt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:nt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Zs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],Is=25,Om="canonry:google-oauth-complete",Gm=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Fm(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const m=t.prior[s],d=t.trailing[s];return m!==null&&d!==null&&m<=0&&d>0?`new in the last ${a}d`:m===null||m<=0?`no prior ${a}d to compare`:d===null?`no value in the last ${a}d`:"comparison unavailable"}if(r===0)return`→ no change vs prior ${a}d`;const o=Math.abs(r*100),i=o<.1?"<0.1%":`${Gm.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function _m(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,u=`${r.startDate} to ${r.endDate}`,m=`Tile percentages compare these ${s} ${o} (${u}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?m:`${m} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function ti(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function si(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function ni(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Um({projectName:t,refreshNonce:s}){const n=ks(),[a,r]=l.useState(!1),[o,i]=l.useState([]),[u,m]=l.useState([]),[d,p]=l.useState([]),[h,j]=l.useState(null),[b,g]=l.useState([]),[f,y]=l.useState([]),[C,z]=l.useState(null),[L,R]=l.useState(""),[c,v]=l.useState(""),[S,D]=l.useState("30"),[T,N]=l.useState(!1),[U,E]=l.useState("30d"),[B,H]=l.useState(["clicks","impressions"]),[ge,ke]=l.useState(!0),[_,se]=l.useState(null),[re,X]=l.useState(0),[Q,P]=l.useState({startDate:"",endDate:"",query:"",page:""}),[G,Y]=l.useState(0),[J,W]=l.useState(!1),[xe,V]=l.useState(0),[le,je]=l.useState(!1),[Fe,Le]=l.useState(""),[Ae,Xe]=l.useState(!0),[lt,we]=l.useState(!1),[et,Ve]=l.useState(!1),[_e,Ue]=l.useState(!1),[Ie,F]=l.useState(!1),[$,q]=l.useState(!1),[me,fe]=l.useState(!1),[Z,Ze]=l.useState(null),[Kt,Ye]=l.useState(!1),[$e,Te]=l.useState(!1),[pt,ct]=l.useState(null),[Oe,Qe]=l.useState(null),[vt,Ke]=l.useState([]),[Ee,qe]=l.useState(new Set),[jt,Ge]=l.useState({}),[It,Gt]=l.useState(new Set),[gt,kt]=l.useState(""),[ht,O]=l.useState(null),[Se,be]=l.useState(""),[ve,ft]=l.useState(!1),[Je,At]=l.useState(!1),[Nt,rs]=l.useState(!1),[is,cs]=l.useState(!1),[rt,ds]=l.useState("indexed"),[dt,bs]=l.useState(null),Wt=!!(Q.query.trim()||Q.page.trim()||dt),zt=dt!==null,Yt=l.useMemo(()=>{if(!dt)return d;const{key:x,dir:M}=dt;return[...d].sort((ae,ue)=>{const Be=x===Ys.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[x],He=x===Ys.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[x];return M==="asc"?Be-He:He-Be})},[d,dt]),wt=Tn({rows:Yt,pageSize:js}),us=le?wt.rows:Yt,Qt=Tn({rows:(pt??[]).filter(x=>x.path.toLowerCase().includes(gt.trim().toLowerCase())),pageSize:js}),[bt,ys]=l.useState([]),[Pt,ms]=l.useState(null),[hs,xs]=l.useState(1),St=l.useMemo(()=>{if(bt.length<2)return null;const x=bt[bt.length-1],M=bt[bt.length-2];return{indexed:x.indexed-M.indexed,notIndexed:x.notIndexed-M.notIndexed}},[bt]);l.useEffect(()=>{xs(1)},[Z,rt,Pt]);const I=l.useMemo(()=>Pt?(Z?.reasonGroups??[]).find(x=>x.reason===Pt):void 0,[Z,Pt]),ee=l.useMemo(()=>Z?rt==="indexed"?Z.indexed:rt==="deindexed"?Z.deindexed:rt==="notIndexed"?Pt?I?.urls??[]:(Z.reasonGroups??[]).length===0?Z.notIndexed:[]:[]:[],[Z,rt,Pt,I]),pe=Math.max(1,Math.ceil(ee.length/Is)),ne=Math.min(Math.max(1,hs),pe),ie=(ne-1)*Is,Me=l.useMemo(()=>Z?.indexed.slice(ie,ie+Is)??[],[Z,ie]),$t=l.useMemo(()=>Z?.notIndexed.slice(ie,ie+Is)??[],[Z,ie]),ut=l.useMemo(()=>Z?.deindexed.slice(ie,ie+Is)??[],[Z,ie]),As=l.useMemo(()=>(I?.urls??[]).slice(ie,ie+Is),[I,ie]),[w,oe]=l.useState(!1),[at,Pe]=l.useState(null),[it,Jt]=l.useState(null),[Tt,Ft]=l.useState(null);function Ht(x,M){const ae=Pu(x),ue=Em(ae);ue?(Jt(ue),Pe(null)):(Jt(null),Pe(ae.message||M))}const Mt=o.find(x=>x.connectionType==="gsc"),vs=(Mt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),vn=vt.length>0?vt:(pt??[]).map(x=>x.path),qn=vn.filter(x=>pt?.some(M=>M.path===x&&M.isSitemapsIndex)).length,ln=qn===1?"Resubmit sitemap index":qn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",k=d.length>0||b.length>0||f.length>0,ce=fl(),Ne=bl();async function _t(x,M=!1){if(!x){m([]),R("");return}Ve(!0);try{const{sites:ae}=await n.fetchQuery({...Tl({client:K,path:{name:t}}),staleTime:M?0:qt});m(ae),R(x.propertyId??ae[0]?.siteUrl??""),Jt(null)}catch(ae){m([]),Ht(ae,"Failed to load Search Console properties")}finally{Ve(!1)}}async function Ut(x){F(!0);const M=x??G;try{const ae=Wt?Bn:js,ue=Wt?0:M,Be={limit:String(ae)};Q.startDate&&(Be.startDate=Q.startDate),Q.endDate&&(Be.endDate=Q.endDate),Q.query&&(Be.query=Q.query),Q.page&&(Be.page=Q.page),ue>0&&(Be.offset=String(ue)),U&&U!=="all"&&!Q.startDate&&(Be.window=U);const He=await n.fetchQuery({...jl({client:K,path:{name:t},query:Be}),staleTime:qt}),tt=He.rows;Wt?(W(!1),p(tt),V(tt.length),je(!0)):(W(ue+tt.length<He.totalMatching),p(tt),V(0),je(!1))}catch(ae){p([]),W(!1),V(0),Pe(ae instanceof Error?ae.message:"Failed to load GSC performance data")}finally{F(!1)}}async function fa(){try{const x={};Q.startDate&&(x.startDate=Q.startDate),Q.endDate&&(x.endDate=Q.endDate),U&&U!=="all"&&!Q.startDate&&(x.window=U);const M=await n.fetchQuery({...vl({client:K,path:{name:t},query:x}),staleTime:qt});j(M)}catch{j(null)}}async function On(x=!1){q(!0);try{const M=Fe.trim()||void 0,ae={limit:"20"};M&&(ae.url=M);const[ue,Be]=await Promise.all([n.fetchQuery({...Il({client:K,path:{name:t},query:ae}),staleTime:x?0:qt}),n.fetchQuery({...$l({client:K,path:{name:t}}),staleTime:x?0:qt})]);g(ue),y(Be)}catch(M){g([]),y([]),Pe(M instanceof Error?M.message:"Failed to load GSC inspection history")}finally{q(!1)}}async function jr(x=!1){Ye(!0);try{const[M,ae]=await Promise.all([n.fetchQuery({...Sl({client:K,path:{name:t}}),staleTime:x?0:qt}),n.fetchQuery({...Cl({client:K,path:{name:t}}),staleTime:x?0:qt}).catch(()=>[])]);Ze(M),ys(ae)}catch(M){Ze(null),ys([]),Pe(M instanceof Error?M.message:"Failed to load coverage data")}finally{Ye(!1)}}async function Nr(x){oe(!0),Pe(null);try{const M=await $r(t,{urls:x}),{succeeded:ae,failed:ue,total:Be}=M.summary;Ce({title:"Indexing requested",detail:ue===0?`${ae} URL${ae!==1?"s":""} submitted for indexing.`:`${ae}/${Be} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(M){Pe(M instanceof Error?M.message:"Failed to request indexing")}finally{oe(!1)}}async function Wo(){oe(!0),Pe(null);try{const x=await $r(t,{urls:[],allUnindexed:!0}),{succeeded:M,failed:ae,total:ue}=x.summary;Ce({title:"Indexing requested",detail:ae===0?`${M} unindexed URL${M!==1?"s":""} submitted for indexing.`:`${M}/${ue} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(x){Pe(x instanceof Error?x.message:"Failed to request indexing")}finally{oe(!1)}}async function ba(){Te(!0),Pe(null);try{const x=await va(t);n.setQueryData(kl({client:K,path:{name:t}}),x),ct(x.sitemaps),Qe(x.summary),Ke(x.preferredSubmissionUrls),qe(new Set),Ge({}),x.sitemaps.length===0&&Ft("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(x){Pe(x instanceof Error?x.message:"Failed to list sitemaps")}finally{Te(!1)}}async function Yo(x){const M=Ee.has(x);if(qe(ae=>{const ue=new Set(ae);return M?ue.delete(x):ue.add(x),ue}),!(M||jt[x])){Gt(ae=>new Set(ae).add(x));try{const ae=await va(t,x);Ge(ue=>({...ue,[x]:ae.sitemaps}))}catch(ae){Pe(ae instanceof Error?ae.message:"Failed to load sitemap files")}finally{Gt(ae=>{const ue=new Set(ae);return ue.delete(x),ue})}}}async function cn(x){if(!vs||x.length===0)return;const M=[...new Set(x)];At(!0),Pe(null),O({completed:0,total:M.length});let ae=0,ue=0,Be=0,He=null;try{for(let Ct=0;Ct<M.length;Ct+=50){const st=M.slice(Ct,Ct+50);try{const ye=await Al(t,st);ae+=ye.summary.accepted,ue+=ye.summary.failed,Be+=st.length,O({completed:Be,total:M.length})}catch(ye){Be+=st.length;const Ps=st.length,jn=M.length-Be,Gn=ye instanceof Error?ye.message:"The batch request failed",Rs=`${ae} accepted, ${ue} failed, ${Ps} unconfirmed, ${jn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;He=`Sitemap submission stopped after a batch request failed. ${Rs} ${Gn}`,Pe(He),Ce({title:"Sitemap resubmission partially completed",detail:Rs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const tt=M.length;Ce({title:ue===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ue===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ae}/${tt} sitemap submissions; ${ue} failed. Indexing is not guaranteed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),be("")}catch(tt){Pe(tt instanceof Error?tt.message:"Failed to submit sitemap to Google")}finally{At(!1),O(null),await ba(),He&&Pe(He)}}async function Jo(){At(!0);const x=pt??[];try{const M=x.filter(ue=>ue.isSitemapsIndex),ae=[];for(let ue=0;ue<M.length;ue+=4)(await Promise.all(M.slice(ue,ue+4).map(async He=>{const tt=jt[He.path];if(tt)return tt;const Ct=await va(t,He.path);return Ge(st=>({...st,[He.path]:Ct.sitemaps})),Ct.sitemaps}))).forEach((He,tt)=>{ae.push(...He.length>0?He.map(Ct=>Ct.path):[M[ue+tt].path])});await cn([...x.filter(ue=>!ue.isSitemapsIndex).map(ue=>ue.path),...ae])}catch(M){Pe(M instanceof Error?M.message:"Failed to load sitemap files"),At(!1)}}async function wr(x){ft(!0),Pe(null);try{await Pl(t,"gsc",x),await yt(n,"google"),i(M=>M.map(ae=>ae.connectionType==="gsc"?{...ae,sitemapUrl:x}:ae)),Ce({title:"Default sitemap updated",detail:x,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(M){Pe(M instanceof Error?M.message:"Failed to set the default sitemap")}finally{ft(!1)}}async function Sr(x){try{await Ne.mutateAsync({projectName:t,projectLabel:t,opts:x?{sitemapUrl:x}:void 0})}catch{}}async function Cr(){Xe(!0),Pe(null);try{const[x,M]=await Promise.all([Yi().catch(()=>null),n.fetchQuery({...lr({client:K,path:{name:t}}),staleTime:qt}).catch(()=>[])]);r(!!x?.google?.configured),i(M);const ae=M.find(ue=>ue.connectionType==="gsc");await Promise.all([_t(ae),Ut(),fa(),On(),jr(),ae?.propertyId?ba():Promise.resolve()])}finally{Xe(!1)}}l.useEffect(()=>{Cr()},[t,s]),l.useEffect(()=>{Y(0),se(null),P(x=>x.startDate||x.endDate?{...x,startDate:"",endDate:""}:x),X(x=>x+1),fa()},[U]);const kr=l.useRef(!1);l.useEffect(()=>{if(!kr.current){kr.current=!0;return}Y(0),wt.setPage(1),Ut(0)},[re]);function ya(x){const M=_===x?null:x;se(M),P(ae=>({...ae,startDate:M??"",endDate:M??""})),X(ae=>ae+1)}const Ar=l.useRef(!1);l.useEffect(()=>{if(!Ar.current){Ar.current=!0;return}Y(0),Ut(0)},[zt]);async function Pr(){if(!a){Pe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),Pe(null),Ft(null);try{let x=function(ye){if(ye.source!==ue||ye.origin!==Be||!ye.data||typeof ye.data!="object")return;const Ps=ye.data;Ps.type!==Om||Ps.connectionType!=="gsc"||st(!0)};const{authUrl:M,redirectUri:ae}=await wl(t,"gsc");if(!M.startsWith("https://accounts.google.com/")){Pe("Unexpected OAuth redirect URL. Please try again.");return}const ue=window.open(M,"_blank","width=600,height=700");if(!ue){window.location.assign(M);return}const Be=ae?new URL(ae).origin:window.location.origin;let He=!1,tt=null;const Ct=()=>{tt!==null&&window.clearInterval(tt),window.removeEventListener("message",x)},st=async ye=>{if(!He){He=!0,Ct(),Ft(ye?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await yt(n,"google"),await Cr()}finally{Ft(null)}}};window.addEventListener("message",x),Ft("Finish the Google consent flow in the popup. This page will refresh automatically."),tt=window.setInterval(()=>{ue.closed&&st(!1)},1e3)}catch(x){Pe(x instanceof Error?x.message:"Failed to start OAuth flow")}finally{we(!1)}}async function Xo(){Pe(null),Ft(null);try{await Nl(t,"gsc"),await yt(n,"google"),i(x=>x.filter(M=>M.connectionType!=="gsc")),m([]),R("")}catch(x){Pe(x instanceof Error?x.message:"Failed to disconnect")}}async function Zo(){if(L){Ue(!0),Pe(null);try{await Ml(t,"gsc",L),await yt(n,"google"),i(x=>x.map(M=>M.connectionType==="gsc"?{...M,propertyId:L}:M)),Ce({title:"GSC property updated",detail:`${t} is now linked to ${L}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(x){Pe(x instanceof Error?x.message:"Failed to save GSC property")}finally{Ue(!1)}}}async function el(){Pe(null),Ft(null);try{await ce.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:T||void 0}}),await yt(n,"gsc")}catch{}}async function Rr(){if(c.trim()){fe(!0),Pe(null),Ft(null);try{const x=await Rl(t,c.trim());await yt(n,"gsc"),z(x),v(""),await On()}catch(x){Pe(x instanceof Error?x.message:"Failed to inspect URL")}finally{fe(!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"})]})}),it&&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:it.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:it.message}),(zs(it.enableUrl)||zs(it.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[zs(it.enableUrl)&&e.jsx("a",{href:zs(it.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 ↗"}),zs(it.indexingApiUrl)&&e.jsx("a",{href:zs(it.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:()=>Jt(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:()=>Pe(null),children:"×"})]}),Tt&&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:[Tt,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Ft(null),children:"×"})]}),Ae?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Mt?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:Mt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",Z?.lastInspectedAt?Bt(Z.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:De(Xo),children:"Disconnect"})]}):e.jsxs(he,{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(de,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:De(Pr),children:lt?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(fs,{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."})]})]})]}),(Mt||k)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(he,{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(ze,{text:`${_m(h?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${Bn.toLocaleString()} matching rows while the table shows ${js} per page.`})]}),h?.window?.startDate&&h.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[h.window.startDate," to ",h.window.endDate,(h.window.daysSinceLatestData??0)>0&&` · latest data ${h.window.daysSinceLatestData} day${h.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{windows:qm,value:U,onChange:x=>{E(x),Y(0),wt.setPage(1)},label:"Search Console time period",formatOption:x=>x==="all"?"All":x}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Ie,onClick:()=>{Y(0),wt.setPage(1),Ut(0),fa()},children:Ie?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const{totals:x,daily:M,trends:ae,periodComparison:ue}=h,He=ei.filter(ye=>B.includes(ye.key)).map(ye=>({dataKey:ye.key,label:ye.label,color:ye.color,axisId:ye.key,inverted:ye.inverted,formatValue:ye.format,trend:ge?ae?.[ye.key]??null:null})),tt=ye=>x[ye]??null,Ct=new Map(M.map(ye=>[ye.date,ye])),st=M.length===0?[]:Mu(M[0].date,M[M.length-1].date).map(ye=>Ct.get(ye)??{date:ye});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:ei.map(ye=>{const Ps=B.includes(ye.key),jn=tt(ye.key),Gn=jn===null;return e.jsxs("button",{type:"button","aria-pressed":Ps,disabled:Gn,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ps?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Gn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{H(Rs=>Rs.includes(ye.key)?Rs.length===1?Rs:Rs.filter(tl=>tl!==ye.key):[...Rs,ye.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:Ps?ye.color:"transparent",border:`1px solid ${ye.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ye.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:jn===null?"—":ye.format(jn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Fm(ue,ye.key,ye.inverted)})]},ye.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:ge,onChange:ye=>ke(ye.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(co,{data:st,xKey:"date",series:He,xTickFormatter:tn,labelFormatter:Ot,onSelectX:ya,selectedX:_})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:M.map(ye=>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":_===ye.date,onClick:()=>ya(ye.date),children:[Ot(ye.date),": ",ye.clicks," clicks, ",ye.impressions," impressions"]},ye.date))}),_&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ot(_)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ya(_),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:Q.startDate,onChange:x=>P(M=>({...M,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:Q.endDate,onChange:x=>P(M=>({...M,endDate:x.target.value}))}),e.jsx(pn,{value:Q.query,onChange:x=>P(M=>({...M,query:x})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(pn,{value:Q.page,onChange:x=>P(M=>({...M,page:x})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),d.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(Ys).map(x=>e.jsx("th",{className:"text-right","aria-sort":dt?.key===x?dt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{wt.setPage(1),bs(M=>M?.key===x?M.dir==="desc"?{key:x,dir:"asc"}:null:{key:x,dir:"desc"})},children:[yl[x],dt?.key===x?dt.dir==="desc"?" ↓":" ↑":""]})},x))]})}),e.jsx("tbody",{children:us.map((x,M)=>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(ea,{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}:${M}`))})]})}),e.jsx(Xs,{page:le?wt.page:Math.floor(G/js)+1,pageSize:js,visibleRows:us.length,totalRows:le?xe:void 0,hasNextPage:le?void 0:J,disabled:Ie,itemLabel:le?"matches":"rows",onPageChange:x=>{if(le){wt.setPage(x);return}const M=(x-1)*js;Y(M),Ut(M)}}),le&&xe>=Bn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Bn.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(he,{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(ze,{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:[Z&&Z.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:w,onClick:()=>{Wo()},children:w?"Requesting…":`Request indexing (${Z.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Kt,onClick:()=>{jr(!0)},children:Kt?"Loading…":"Reload saved coverage"})]})]}),Z&&Z.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const x=Z.summary.indexed+Z.summary.notIndexed,M=x>0?Z.summary.indexed/x:0,ae=x>0?Z.summary.notIndexed/x:0,ue=54,Be=2*Math.PI*ue,He=Be*(1-M),tt=Be*ae,Ct=Be*M;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:ue,fill:"none",stroke:as.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ue,fill:"none",stroke:Zs.positiveDeep,strokeWidth:"14",strokeDasharray:Be,strokeDashoffset:He,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),Z.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ue,fill:"none",stroke:as.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${Be-tt}`,strokeDashoffset:-Ct,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:[(M*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:Z.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:Z.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(Z.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(Z.reasonGroups??[]).length," ",(Z.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),Z.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:Z.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 M=x==="indexed"?Z.indexed.length:x==="notIndexed"?Z.notIndexed.length:Z.deindexed.length,ae=x==="indexed"?"Indexed":x==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":rt===x,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${rt===x?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{ds(x),ms(null)},children:[ae," (",M,")"]},x)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[rt==="indexed"&&Z.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:Me.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))})]}),rt==="notIndexed"&&!Pt&&(Z.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:(Z.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:()=>ms(x.reason),onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),ms(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))})]}),rt==="notIndexed"&&!Pt&&(Z.reasonGroups??[]).length===0&&Z.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:$t.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))})]}),rt==="notIndexed"&&Pt&&(()=>{const x=(Z.reasonGroups??[]).find(M=>M.reason===Pt);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:()=>ms(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(A,{type:"button",variant:"outline",size:"sm",disabled:w,onClick:()=>{Nr(x.urls.map(M=>M.url))},children:w?"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:As.map(M=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:M.url}),e.jsx("td",{className:"text-secondary",children:M.crawlTime?M.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:w,onClick:()=>{Nr([M.url])},title:"Request indexing",children:"Index"})})]},M.id))})]})]}):null})(),rt==="deindexed"&&Z.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:ut.map((x,M)=>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}-${M}`))})]}),(rt==="indexed"&&Z.indexed.length===0||rt==="notIndexed"&&!Pt&&Z.notIndexed.length===0||rt==="deindexed"&&Z.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Xs,{page:ne,pageSize:Is,visibleRows:Math.min(Is,ee.length-ie),totalRows:ee.length,onPageChange:xs,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":is,onClick:()=>cs(x=>!x),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:is?"Hide snapshots":bt.length>0?`View ${bt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",Z.summary.indexed.toLocaleString()," indexed, ",Z.summary.notIndexed.toLocaleString()," not indexed.",St&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",St.indexed>=0?"+":"",St.indexed.toLocaleString()," indexed, ",St.notIndexed>=0?"+":"",St.notIndexed.toLocaleString()," not indexed."]})]}),is&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:bt.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:bt.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:Kt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(he,{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(ze,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:$e||!Mt?.propertyId,onClick:()=>{ba()},children:$e?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Se,onChange:x=>be(x.target.value),onKeyDown:x=>x.key==="Enter"&&void cn([Se.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!vs||Je||!Se.trim(),onClick:()=>{cn([Se.trim()])},children:Je?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!vs||Je||vn.length===0,onClick:()=>{cn(vn)},children:Je?"Resubmitting…":ln}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!vs||Je||!pt?.length,onClick:()=>{Jo()},children:"Resubmit all files"}),Oe&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Oe.indexes," index",Oe.indexes===1?"":"es",", ",Oe.files," file",Oe.files===1?"":"s"]}),ht&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",ht.completed,"/",ht.total]})]}),!vs&&Mt&&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:De(Pr),children:"Reconnect"})]}),pt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:pt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(pn,{value:gt,onChange:x=>{kt(x),Qt.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:Qt.rows.flatMap(x=>{const M=ti(x),ae=si(x),ue=ni(x),Be=jt[x.path]??[],He=Ee.has(x.path),tt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(ea,{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":He,"aria-label":`${He?"Collapse":"Expand"} files in ${x.path}`,onClick:()=>{Yo(x.path)},children:It.has(x.path)?"Loading…":`${He?"▾":"▸"} Index${jt[x.path]?` (${Be.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ue}),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:M.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ae||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!vs||Je,onClick:()=>{cn([x.path])},children:x.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Mt?.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:ve,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{wr(x.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Ne.isPending,onClick:()=>{Sr(x.path)},children:"Inspect URLs"})]})})]},x.path),Ct=x.isSitemapsIndex&&He?Be.map(st=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(ea,{value:st.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:ni(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:ti(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:si(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:!vs||Je,onClick:()=>{cn([st.path])},children:"Resubmit"}),Mt?.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:ve,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{wr(st.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Ne.isPending,onClick:()=>{Sr(st.path)},children:"Inspect URLs"})]})})]},`${x.path}:${st.path}`)):[];return[tt,...Ct]})})]}),e.jsx(Xs,{page:Qt.page,pageSize:js,visibleRows:Qt.rows.length,totalRows:Qt.totalRows,onPageChange:Qt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(he,{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:c,onChange:x=>v(x.target.value),onKeyDown:x=>x.key==="Enter"&&void Rr()}),e.jsx(A,{type:"button",size:"sm",disabled:me||!Mt?.propertyId||!c.trim(),onClick:De(Rr),children:me?"Inspecting…":"Inspect URL"})]}),C&&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:C.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:C.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:Ir(C.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Bt(C.crawlTime)})]})]})]}),e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:$,onClick:()=>{On(!0)},children:$?"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:Fe,onChange:x=>Le(x.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:$,onClick:()=>{On(!0)},children:"Apply filter"})]}),b.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:b.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:Ir(x.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Bt(x.inspectedAt)})]},x.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(he,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),f.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:f.map(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:Bt(x.transitionDate)})]},`${x.url}:${x.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Mt&&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:()=>rs(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 ${Nt?"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"})]})}),Nt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(he,{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(ze,{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:L,disabled:et||u.length===0,onChange:x=>R(x.target.value),children:u.length===0?e.jsx("option",{value:"",children:et?"Loading properties…":"No properties available"}):u.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(A,{type:"button",size:"sm",variant:"outline",disabled:et,onClick:()=>{_t(Mt,!0)},children:et?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!L||_e,onClick:De(Zo),children:_e?"Saving…":"Save property"})]})]})]}),e.jsxs(he,{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=>D(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:T,onChange:x=>N(x.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:ce.isPending||!Mt.propertyId,onClick:De(el),children:ce.isPending?"Queueing…":"Queue sync"}),!Mt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Bm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Vm({projectName:t,projectId:s}){const n=ks(),[a,r]=l.useState(null),[o,i]=l.useState(null),[u,m]=l.useState(!1),d=Re(lr({client:K,path:{name:t}})),p=d.data?.find(V=>V.connectionType==="gbp"),h=!!p,j=a?{locationName:a}:void 0,b=Re({...Ll({client:K,path:{name:t}}),enabled:h}),g=Re({...Dl({client:K,path:{name:t},query:j}),enabled:h}),f=Re({...El({client:K,path:{name:t},query:j}),enabled:h}),y=Re({...ql({client:K,path:{name:t},query:j}),enabled:h}),C=Re({...Ol({client:K,path:{name:t},query:j}),enabled:h}),z=Re({...Gl({client:K,path:{name:t},query:j}),enabled:h}),L=Re({queryKey:["gbp-section-insights",t],queryFn:()=>Fl(t),enabled:h});function R(){yt(n,"gbp")}const c=Et({..._l(),onSuccess:V=>{Ji({id:V.runId,projectId:s,kind:Gs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Ce({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(Xi,sa,sa),S=Object.values(v.runs).some(V=>V.kind===Gs["gbp-sync"]&&V.projectId===s),D=c.isPending||S,T=Et({...Ul(),onSuccess:()=>R()});if(l.useEffect(()=>{if(!a||!b.data)return;const V=b.data.locations.filter(le=>le.selected);(V.length<=1||!V.some(le=>le.locationName===a))&&r(null)},[a,b.data]),l.useEffect(()=>{if(!o||!b.data)return;(a?[a]:b.data.locations.filter(le=>le.selected).map(le=>le.locationName)).includes(o)||i(null)},[o,b.data,a]),d.isLoading)return null;if(!p){const V=[{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(he,{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:V.map((le,je)=>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:je+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:le.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:le.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:le.note})]})]},le.title))})]})})}const N=g.data,U=b.data?.locations??[],E=U.filter(V=>V.selected),B=f.data?.keywords??[],H=y.data?.lodging??[],ge=C.data?.placeActions??[],ke=z.data?.places??[],_=U.length>0?U[0].accountName:p.domain,se=a?U.find(V=>V.locationName===a)?.displayName??null:null,re=a?U.filter(V=>V.locationName===a):E,X=new Set(re.map(V=>V.locationName)),Q=H.filter(V=>X.has(V.locationName)),P=ge.filter(V=>X.has(V.locationName)),G=ke.filter(V=>X.has(V.locationName)),Y=new Set(E.map(V=>V.locationName)),J=a?B:B.filter(V=>Y.has(V.locationName)),W=!a&&E.length>1,xe=(L.data??[]).filter(V=>!V.dismissed&&Bm.has(V.type)&&(!se||V.query===se||V.query===a||V.title.startsWith(se)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(he,{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(ze,{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(de,{tone:"positive",children:"Connected"}),!te()&&e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:D,onClick:()=>c.mutate({client:K,path:{name:t},body:{}}),children:D?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[_?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:_})," · "]}):null,b.data?`${b.data.totalSelected} of ${b.data.totalDiscovered} locations tracked`:"Loading locations…"]}),E.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:V=>r(V.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"}),E.map(V=>e.jsx("option",{value:V.locationName,children:V.displayName},V.id))]})]}),E.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:[xe.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),xe.map(V=>e.jsx("div",{className:["insight-card",nh(V.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:[V.title,V.recommendation?.reason&&e.jsx(ze,{text:V.recommendation.reason})]})},V.id))]}),N&&e.jsx(oh,{performance:N.performance,freshness:N.freshness,timeseries:N.timeseries}),N?.profileCompleteness&&e.jsx(Km,{summary:N.profileCompleteness}),re.length>0&&e.jsx(zm,{locations:re,lodging:Q,places:G,placeActions:P,expandedLocation:o,onToggleExpanded:V=>{i(le=>le===V?null:V)}}),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"}),f.data&&f.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[f.data.thresholdedPct,"% privacy-thresholded"]})]}),J.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"}),W&&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:J.slice(0,25).map(V=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:V.keyword}),W&&e.jsx("td",{className:"text-muted",children:U.find(le=>le.locationName===V.locationName)?.displayName??V.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:V.valueCount!==null?V.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",V.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[V.periodStart,"–",V.periodEnd]})]},`${V.locationName}:${V.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:()=>m(V=>!V),"aria-expanded":u,children:[e.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"})," Manage locations (",U.length,")"]}),u&&e.jsx("div",{className:"mt-3",children:U.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!te()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:U.map(V=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:V.displayName}),e.jsx("td",{className:"text-muted",children:V.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(de,{tone:V.selected?"positive":"neutral",children:V.selected?"Tracked":"Not tracked"})}),!te()&&e.jsx("td",{className:"text-right",children:e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:T.isPending,onClick:()=>T.mutate({client:K,path:{name:t,locationName:V.locationName},body:{selected:!V.selected}}),children:V.selected?"Untrack":"Track"})})]},V.id))})]})})]})]})})}function Km({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:wn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:wn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:wn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:wn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:wn(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(ze,{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 ${sh(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function zm({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(d=>[d.locationName,d])),u=new Map(n.map(d=>[d.locationName,d])),m=new Map;for(const d of a){const p=m.get(d.locationName)??[];p.push(d),m.set(d.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(ze,{text:te()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(d=>{const p=i.get(d.locationName)??null,h=u.get(d.locationName)??null,j=m.get(d.locationName)??[],b=r===d.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:d.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:d.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(de,{tone:d.selected?"positive":"neutral",children:d.selected?"Tracked":"Not tracked"}),d.openStatus&&d.openStatus!=="OPEN"&&e.jsx(de,{tone:d.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:ko(d.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Hm,{location:d})}),e.jsx("td",{children:e.jsx(Wm,{lodging:p})}),e.jsx("td",{children:e.jsx(Jm,{place:h,mapsUri:d.mapsUri})}),e.jsx("td",{children:e.jsx(Zm,{actions:j})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>o(d.locationName),children:b?"Hide":"Details"})})]}),b&&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(th,{location:d,lodging:p,place:h,placeActions:j})})})]},d.id)})})]})})]})}function Qm(t){return[{label:"Description",tone:Qs(t.description)?"positive":"neutral",value:Qs(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Qs(t.primaryPhone)?"positive":"neutral",value:Qs(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Qs(t.websiteUri)?"positive":"neutral",value:Qs(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=Qm(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(de,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Wm({lodging:t}){return e.jsx(dr,{...Ym(t)})}function Ym(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 Jm({place:t,mapsUri:s}){return e.jsx(dr,{...Xm(t,s)})}function Xm(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 Zm({actions:t}){return e.jsx(dr,{...eh(t)})}function eh(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 dr({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(de,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function th({location:t,lodging:s,place:n,placeActions:a}){const r=s?rh(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Ia,{title:"Owner profile · Business Information",children:[e.jsx(Lt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Lt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Lt,{label:"Description",value:Qs(t.description)?t.description:"Not returned"}),e.jsx(Lt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Lt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Lt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Lt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Lt,{label:"Open status",value:ko(t.openStatus)}),e.jsx(Lt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Ia,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{label:"Last checked",value:ai(s.syncedAt)}),e.jsx(Lt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Lt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(Ia,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Lt,{label:"Places tier",value:n.tier}),e.jsx(Lt,{label:"Last checked",value:ai(n.syncedAt)}),e.jsx(Lt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[ua(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[ua(o.providerType),o.uri?` · ${ah(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function Ia({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 Lt({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 wn(t,s,n){return t===s?"positive":t===0?n:"caution"}function sh(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function nh(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Qs(t){return typeof t=="string"&&t.trim().length>0}function ko(t){return t?ua(t):"Not returned"}function ua(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function ah(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ai(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function rh(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&ih(n)).map(([s])=>ua(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function ih(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function oh({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Bl.filter(g=>(a[g]??0)>0),o=Vl.filter(g=>(a[g]??0)>0),i=Object.keys(a).filter(g=>(a[g]??0)>0&&Kl(g)==="other").sort((g,f)=>(a[f]??0)-(a[g]??0)),u=Object.keys(a).filter(g=>(a[g]??0)===0).sort(),m=n.map(g=>{const f={date:g.date};for(const[y,C]of Object.entries(g.metrics))f[y]=C;return f}),d=n.find(g=>g.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,h=m.length>0,j=s.dataThroughDate?`Data through ${Ot(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,b=[...r,...i];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),j&&e.jsx("span",{className:"text-[11px] text-muted",children:j})]}),!h||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(ri,{data:m,metrics:r,kind:"line",firstPending:d,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:b.map(g=>e.jsxs("span",{className:"text-sm text-secondary",children:[na(g)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[g]??0).toLocaleString()})]},g))})]})]}),h&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(ri,{data:m,metrics:o,kind:"area",firstPending:d,lastDate:p})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",u.map(g=>na(g)).join(", ")]})]})}function ri({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ca,{stroke:la,vertical:!1}),e.jsx(an,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:tn,minTickGap:24}),e.jsx(rn,{tick:Vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...ss,labelFormatter:Ot,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),na(String(i??""))]}),e.jsx(da,{wrapperStyle:{fontSize:11,color:as.text},formatter:o=>na(o)}),a&&r&&e.jsx(Ya,{x1:a,x2:r,fill:as.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:as.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Ws,{type:"monotone",dataKey:o,stroke:nt[i%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Ls,{type:"monotone",dataKey:o,stackId:"reach",stroke:nt[i%nt.length],fill:nt[i%nt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function lh(t){return uo(Cs(String(t)))}function ch(t){return qs(Cs(String(t)))}function $a({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[o,i]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":o?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(yu,{className:"h-3.5 w-3.5","aria-hidden":!0})}),o&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Vn=js;function dn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Ta(t){return t.toLocaleString()}function dh(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function uh(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 mh(t){const s=t.filter(n=>n.kind===Gs["backlink-extract"]&&!Zi(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function hh(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),o=a%60;return o===0?`${r}m`:`${r}m ${o}s`}function xh({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[u,m]=l.useState(null),[d,p]=l.useState(null),[h,j]=l.useState(null),[b,g]=l.useState(Date.now()),[f,y]=l.useState(0),[C,z]=l.useState(!0),[L,R]=l.useState(!1),[c,v]=l.useState(null),S=l.useCallback(async()=>{z(!0),v(null);try{const[_,se,re,X,Q]=await Promise.all([zl().catch(()=>null),Ql(t,{excludeCrawlers:!0}).catch(()=>null),Hl(t,{limit:Vn,offset:f,excludeCrawlers:!0}).catch(G=>{if(G instanceof en&&G.code==="NOT_FOUND")return null;throw G}),Wl(t).catch(()=>[]),Yl(t).catch(()=>[])]);m(_),n(se),r(re),i(X);const P=mh(Q);p(P)}catch(_){v(_ instanceof Error?_.message:"Failed to load backlinks")}finally{z(!1)}},[t,f]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!d)return;const _=d.id;let se=!1;const re=async()=>{try{const Q=await Wa(_);if(se)return;Zi(Q.status)?(p(null),j(Q),await S()):p(P=>P?.id===Q.id?{...P,...Q}:P)}catch{}},X=window.setInterval(()=>{re()},3e3);return()=>{se=!0,window.clearInterval(X)}},[d,S]),l.useEffect(()=>{if(!d)return;const _=window.setInterval(()=>g(Date.now()),1e3);return()=>window.clearInterval(_)},[d]),l.useEffect(()=>{if(!h||h.status==="failed")return;const _=window.setTimeout(()=>j(null),1e4);return()=>window.clearTimeout(_)},[h]);async function D(){R(!0),v(null);try{const _=await Xl(t);p(_)}catch(_){_ instanceof en&&_.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(_ instanceof Error?_.message:"Failed to trigger extract")}finally{R(!1)}}const T=l.useMemo(()=>o.slice().sort((_,se)=>_.queriedAt.localeCompare(se.queriedAt)).map(_=>({date:_.queriedAt,linkingDomains:_.totalLinkingDomains})),[o]),N=a?.rows??[],U=a?.total??0,E=s?.excludedLinkingDomains??0,B=Math.floor(f/Vn)+1;return l.useEffect(()=>{f>0&&f>=U&&y(0)},[f,U]),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"})]})}),c&&e.jsx(he,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:c})}),d&&e.jsx(he,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(fu,{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(de,{tone:"neutral",children:d.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[hh(d.startedAt??null,d.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",b]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),h&&!d&&e.jsx(he,{className:`surface-card p-4 mb-4 ${h.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[h.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(oo,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${h.status==="failed"?"text-negative":"text-positive"}`,children:h.status==="failed"?"Extract failed":"Extract complete"}),h.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Jl(h.error)}):h.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return C?e.jsx(he,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):ge()}function ge(){const _=s!==null&&s.totalLinkingDomains>0,se=h?.status==="failed",re=s!==null&&s.totalLinkingDomains===0&&!se,X=u?.status==="ready",Q=u?.status==="failed",P=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return _?ke(e.jsxs(e.Fragment,{children:[!te()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:L||d!==null,onClick:De(D),children:[e.jsx(lo,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),d?"Extract running…":L?"Queuing…":"Re-run extract"]}),e.jsx($a,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!te()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:dn("/backlinks"),children:"Open admin"})})]})):e.jsx(he,{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(bu,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!u&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:dn("/backlinks"),children:"Set up backlinks"})})})]}),P&&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 (",u.status,u.phaseDetail?` — ${u.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:dn("/backlinks"),children:"View sync status"})})})]}),Q&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:u.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:dn("/backlinks"),children:"Go to Backlinks admin"})})})]}),X&&!P&&!re&&!se&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:u.release})," is ready. Run an extract for this project."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:L||d!==null,onClick:De(D),children:[e.jsx(ia,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),d?"Extract running…":L?"Queuing…":"Run extract"]}),e.jsx($a,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),se&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!te()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:dn("/backlinks"),children:"Go to Backlinks admin"})})})]}),re&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:dn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:L||d!==null,onClick:De(D),children:[e.jsx(ia,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),d?"Extract running…":L?"Queuing…":"Re-run extract"]}),e.jsxs($a,{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 ke(_){if(!s)return null;const se="Linking hosts",re="linking hosts",X="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:Ta(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 ",re]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ta(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",re," 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:dh(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",re," 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"})," · ",X," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",uh(s.queriedAt),E>0&&e.jsxs(e.Fragment,{children:[" · ",E," excluded domain",E===1?"":"s"]})]}),T.length>=2&&e.jsxs(he,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:T,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:nt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:nt[0],stopOpacity:0})]})}),e.jsx(an,{dataKey:"date",tick:Vt,stroke:ls,tickFormatter:lh}),e.jsx(rn,{tick:Vt,stroke:ls,allowDecimals:!1}),e.jsx(on,{contentStyle:ss.contentStyle,labelStyle:ss.labelStyle,itemStyle:ss.itemStyle,labelFormatter:ch}),e.jsx(Ls,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:nt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(he,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:se})]})}),e.jsxs("tbody",{children:[N.map(Q=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:Q.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Ta(Q.numHosts)})]},Q.linkingDomain)),N.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:E>0&&U===0?`Every referring domain in this ${X} was a crawler/proxy host (${E} hidden).`:`No referring domains in this ${X}.`})})]})]})}),e.jsx(Xs,{page:B,pageSize:Vn,visibleRows:N.length,totalRows:U,onPageChange:Q=>y((Q-1)*Vn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:_})]})}}function ph({projectName:t}){const s=Re({...Zl({client:K,path:{name:t}}),staleTime:eo}),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:cr(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:r,providersMentioning:o,providersConfigured:i}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",i," engines",e.jsx(ze,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",o," of ",i," engine answers",e.jsx(ze,{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(gh,{data:n}),e.jsx(fh,{data:n}),n.competitorGaps.length>0&&e.jsx(jh,{data:n})]})}function gh({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:o}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Kn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Kn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Kn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Kn,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function Kn({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function fh({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const r of a.providers)n.add(r.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(bh,{}),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($n,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(o=>o.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(vu,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(yh,{provider:r})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function bh(){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(xn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xn,{active:!1,tone:"cited"}),e.jsx(xn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function yh({provider:t}){const s=vh(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(xn,{active:t.cited,tone:"cited"}),e.jsx(xn,{active:t.mentioned,tone:"mentioned"})]})}function vh(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 xn({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 jh({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(ze,{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($n,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Dn="__cited__",En="__mentioned__",ns="__mentionShare__";function Ao(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Cs(n),end:Cs(a),sweepCount:s.sweepCount??1}}function ma(t){const s=Ao(t);if(!s)return"Sweep date unavailable";const n=qs(s.start),a=qs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Nh(t){const s=Ao(t);return s?uo(s.start):""}function yn(t){return t.trim().toLowerCase()}function tr(t){return Math.round(t*1e3)/10}function sr(t){return t.byProvider??{}}function wh(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const m=s==="cited"?Dn:En,d=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(h=>({date:h.startDate,[m]:tr(h[d])})),series:[m],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(m=>Object.keys(sr(m))))].sort();return{rows:t.buckets.map(m=>{const d={date:m.startDate},p=sr(m);for(const h of i){const j=p[h];d[h]=j?tr(j[o]):null}return d}),series:i,hasData:a,singleBucket:r}}function Po(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Sh(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Ch(t){return t.servedModelAttribution??{}}function kh(t){return t.modelServiceMismatch??{}}function Ah(t){return t.modelPointerChanges??{}}function Ph(t){return t.length>0?t.join(", "):null}function ii(t,s){const n=yn(s);return Object.entries(t).find(([a])=>yn(a)===n)?.[1]}function Ns(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 Rh(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!ii(sr(a),s))continue;const r=Po(a);return r?ii(r,s)??null:null}return null}function Ih(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const o=s.get(r.bucketStartDate)??[];o.push({provider:n,event:r}),s.set(r.bucketStartDate,o)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,o)=>r.provider.localeCompare(o.provider)||r.event.observedAt.localeCompare(o.event.observedAt))}))}function $h(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const o=r.events.filter(i=>!i.fromPreWindowAnchor);for(const i of r.events)i.fromPreWindowAnchor&&n.push({provider:a,event:i});o.length>0&&(s[a]={...r,events:o})}return{buckets:Ih(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Th(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 Mh(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Lh(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[ns]:r?.rate==null?null:tr(r.rate)}}),n=s.map(a=>a[ns]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[ns],hasData:n.length>0,singleBucket:n.length===1}}function Dh(t,s,n){return s==="mentionShare"?Lh(t):wh(t,s,n)}function oi(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 li(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function ci(t){return t>0?`+${t}`:`${t}`}function Eh(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${ci(n.delta)} on ${li(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${ci(s.delta)} on ${li(s.date)})`}const qh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Oh=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Gh=[{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."}],ur=nt[2],Fh="var(--chart-tooltip-bg)",_h={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Ss(t){const s=yn(t);return _h[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Ds(t){return Math.round(t*10)/10}function Uh(t){return t===Dn||t===En||t===ns}function Ro(t){return t===Dn?"Cited":t===En?"Mentioned":t===ns?"Mention share":Ss(t)}function kn(t,s){return t===Dn?Zs.positive:t===En?nt[1]:t===ns?ur:wu(yn(t),s)}function Bh(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Vh(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
+
`)}function ga(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function ta(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${ga(s)}`:"Mention share":"Mentioned"}function Mn(t){return t==="cited"?"citationRate":"mentionRate"}function Io(t,s){return s==="cited"?t.cited:t.mentionedCount}function $o(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 To(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function nr(t){const s=Po(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>yn(a).localeCompare(yn(r))).map(([a,r])=>`${Ss(a)}: ${Ns(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Kh(t){return t.some(({event:s})=>s.to.status==="mixed")?Zs.caution:t.some(({event:s})=>s.to.status==="unknown")?Zs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:Zs.positive}function zh(t,s,n){const a=To(t,s);return a?ma(a):qs(Cs(n))}function Qh({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:u}){const m=l.useId(),d=Object.entries(o).sort(([h],[j])=>h.localeCompare(j)),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":m,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:m,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:h,events:j})=>j.map(({provider:b,event:g})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:zh(u,h,g.observedAt)}),e.jsxs("span",{children:[Ss(b),": ",Ns(g.from)," → ",Ns(g.to)]})]},`${b}-${g.observedAt}-${g.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:h,event:j})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",qs(Cs(j.observedAt))]}),e.jsxs("span",{children:[Ss(h),": ",Ns(j.from)," → ",Ns(j.to),j.anchorObservedAt?` (last seen ${Ns(j.from)} on ${qs(Cs(j.anchorObservedAt))})`:""]})]},`before-${h}-${j.observedAt}`))})]}),a.map(h=>e.jsxs("p",{className:"trend-model-evidence-note",children:[Ss(h.provider),": showing the most recent ",h.shown," of ",h.total," changes."]},`truncated-${h.provider}`)),r.map(h=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",Ss(h)," change."]},`incomplete-${h}`)),d.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:d.map(([h,j])=>{const b=Ph(j.latestServedModelIds),g=i[h];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:qs(Cs(j.latestObservation.observedAt))}),e.jsxs("span",{children:[Ss(h),": ",b??Ns(j.latestObservation.state),g?` — not the ${Ns(g.configured)} you selected`:""]})]},`served-${h}`)})})]})]})}function di(t){return t===null?"no data":`${t}%`}function Ma(t){return t==null?"undefined":`${Ds(t*100)}%`}function Hh({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=To(o,s);if(!i)return null;if(a==="mentionShare"){const m=i.mentionShare.projectMentionSnapshots,d=i.mentionShare.competitorMentionSnapshots,p=m+d,h=i.mentionShare.rate==null?null:Ds(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:ma(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:ur},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",ga(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:di(h)})]}),p>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",m," / ",p," brand mentions. Competitors ",d,"."]}):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:nr(i)})]})}const u=r==="byProvider"?(n??[]).filter(m=>m.dataKey!==void 0):[{dataKey:a==="cited"?Dn:En,value:Ds(i[Mn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:ma(i)}),u.map((m,d)=>{const p=String(m.dataKey??m.name??""),h=r==="byProvider"?$o(i,p,a):null,j=h?.count??Io(i,a),b=h?.total??i.total,g=typeof m.value=="number"?m.value:Ds(h?h.rate*100:i[Mn(a)]*100),f=m.color??kn(p,d);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:f},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ro(p)}),e.jsx("span",{className:"trend-tooltip-value",children:di(g)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[j," / ",b," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${p}-${d}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:nr(i)})]})}function Wh({buckets:t,metric:s,mode:n,series:a}){const r=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[ta(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(o=>{let i;if(s==="mentionShare"){const u=o.mentionShare.projectMentionSnapshots,m=o.mentionShare.competitorMentionSnapshots,d=u+m,p=ga(o.mentionShare.scope);i=d>0?`${Ma(o.mentionShare.rate)} mention share for ${p}, ${u} of ${d} brand mentions were you`:`mention share undefined for ${p}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(u=>{const m=$o(o,u,s);return m?`${Ss(u)} ${Ma(m.rate)} ${ta(s).toLowerCase()}, ${m.count} of ${m.total} snapshots`:`${Ss(u)} no data`}).join("; "):i=`${Ma(o[Mn(s)])} ${ta(s).toLowerCase()}, ${Io(o,s)} of ${o.total} snapshots`;return i+=`; ${nr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:ma(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function La({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const o=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(i=>{const u=s===i.value,m=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":u,"aria-describedby":m,className:`segmented-option ${u?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:m,className:"sr-only",children:i.description})]},i.value)})})}function Yh({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[u,m]=l.useState("byProvider"),d=l.useMemo(()=>Vh(s),[s]),p=Re({queryKey:["analytics-metrics",t,a,d,n],queryFn:()=>ec(t,a),staleTime:eo}),h=p.data??null,j=p.error,b=o==="mentionShare"?"overall":u,g=l.useMemo(()=>h?Dh(h,o,b):null,[h,o,b]),f=h?Sh(h):null,y=l.useMemo(()=>$h(f??{}),[f]),C=l.useMemo(()=>Th(f??{}),[f]),z=l.useMemo(()=>Mh(f??{}),[f]),L=l.useMemo(()=>Object.entries(f??{}).filter(([,Q])=>Q.anchorUnavailable).map(([Q])=>Q).sort(),[f]),R=l.useMemo(()=>h?Ch(h):{},[h]),c=l.useMemo(()=>h?kh(h):{},[h]),v=l.useMemo(()=>h?tc(Ah(h)):null,[h]),S=o!=="mentionShare"&&b==="byProvider",D=h?.buckets??[],T=D[D.length-1]?.mentionShare.scope??h?.mentionShareScope??"pooled",N=ta(o,T),U=o==="cited"?Zs.positive:o==="mentionShare"?ur:nt[1],E=S?as.textDim:U,B=l.useMemo(()=>{const Q=new Map(D.map(P=>[P.startDate,Nh(P)]));return P=>Q.get(String(P))??""},[D]),H=o==="mentionShare"?g?oi(g.rows,ns):null:D.length>0?Ds(D[D.length-1][Mn(o)]*100):null,ge=o==="mentionShare"?g?Bh(g.rows,ns):null:D.length>0?Ds(D[0][Mn(o)]*100):null,ke=o==="mentionShare"?g?.rows.filter(Q=>typeof Q[ns]=="number").length??0:D.length,_=H!==null&&ge!==null&&ke>1?Ds(H-ge):null,se=s.length,re=e.jsxs(e.Fragment,{children:[v?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:v.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(ze,{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:E},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:N}),S&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[H,"%"]}),_!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${_>0?"text-positive-400":_<0?"text-negative-400":"text-muted"}`,children:[_>0?"+":"",_.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(La,{options:Gh,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(La,{options:Oh,value:u,onChange:m,ariaLabel:"Series"}),e.jsx(La,{options:qh,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let X;if(j)X=e.jsx("p",{className:"text-sm text-negative-400",children:cr(j)});else if(p.isLoading&&!h)X=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&se===0)X=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!h||!g)X=null;else{const{rows:Q,series:P,hasData:G}=g,Y=Eh(h.queryChanges);if(!G)X=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${ga(T)} in this window yet.`:"Run a sweep to start tracking citations and mentions over time."});else if(S&&P.length===0)X=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 J=`${N} rate across ${Q.length} ${Q.length===1?"sweep":"sweeps"}. Latest ${H}%${_!==null?`, ${_>=0?"up":"down"} ${Math.abs(_).toFixed(1)} points over the period`:""}.`;X=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:J}),e.jsx(Wh,{buckets:D,metric:o,mode:b,series:P}),S&&P.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:P.map((W,xe)=>{const V=oi(Q,W),le=Rh(D,W),je=f===null?"Attribution unavailable":le?Ns(le):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:kn(W,xe)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Ro(W)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),je]})]}),V!==null&&e.jsxs("span",{className:"trend-legend-value",children:[V,"%"]})]},W)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${N} trend chart over ${Q.length} ${Q.length===1?"bucket":"buckets"}`,children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:Q,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ca,{stroke:la,vertical:!1}),e.jsx(an,{dataKey:"date",tick:Vt,tickLine:!1,axisLine:{stroke:ls},tickFormatter:B,minTickGap:24}),e.jsx(rn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:W=>`${W}%`,tick:Vt,tickLine:!1,axisLine:!1,width:40}),e.jsx(on,{cursor:{stroke:ls,strokeWidth:1},content:e.jsx(Hh,{metric:o,mode:b,buckets:D})}),y.buckets.map(({bucketStartDate:W,events:xe})=>e.jsx(Ru,{x:W,stroke:Kh(xe),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${W}`)),P.map((W,xe)=>e.jsx(Ws,{type:"monotone",dataKey:W,name:W,stroke:kn(W,xe),strokeDasharray:W===ns?"5 4":void 0,strokeWidth:Uh(W)?2.5:2,dot:W===ns?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:kn(W,xe),strokeWidth:1.5}:{r:2.5,fill:kn(W,xe),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Fh},connectNulls:W!==ns,isAnimationActive:!1},W))]})})}),e.jsx(Qh,{partition:y,available:f!==null,counts:C,truncated:z,incompleteHistory:L,served:R,mismatch:c,buckets:D}),Y&&e.jsx("p",{className:"visibility-trend-note",children:Y})]})}}return e.jsxs("section",{className:"visibility-trend",children:[re,X]})}const ui=new Set([Rn.queued,Rn.running]);function Jh({projectName:t}){const s=ks(),[n,a]=l.useState(""),[r,o]=l.useState(""),[i,u]=l.useState(""),[m,d]=l.useState("__default__"),[p,h]=l.useState(null),j=Re({...sc({client:K,path:{name:t}}),staleTime:6e4}),b=Re({...nc({client:K}),staleTime:6e4}),g=Re({...ac({client:K,path:{name:t},query:{limit:20}}),refetchInterval:N=>N.state.data?.runs.some(U=>ui.has(U.status))?3e3:!1}),f=g.data?.runs??[];l.useEffect(()=>{!p&&f[0]&&h(f[0].id)},[f,p]);const y=f.find(N=>N.id===p)??null,C=Re({...rc({client:K,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:y&&ui.has(y.status)?3e3:!1}),z=C.data??null,L=l.useMemo(()=>ex(n),[n]),R=j.data?.locations??[],c=l.useMemo(()=>{const N=new Map((b.data?.providerCatalog??[]).map(U=>[U.name,U]));return(b.data?.providers??[]).filter(U=>U.configured&&N.get(U.name)?.mode==="api").map(U=>({...U,catalog:N.get(U.name)}))},[b.data]),v=!b.isLoading&&c.length===0,S=c.find(N=>N.name===r)??null;l.useEffect(()=>{r&&!S&&(o(""),u(""))},[r,S]);const D=Et({...ic(),onSuccess:async N=>{h(N.id),a(""),u(""),await ax(s),Ce({title:"Research batch saved",detail:`${N.totalQueries} quer${N.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${N.id}`,dedupeMode:"replace"})},onError:N=>{Ce({title:"Could not start research",detail:N instanceof Error?N.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function T(){if(L.length===0||L.length>50||v||D.isPending||te())return;const N=m==="__default__"?void 0:m==="__none__"?null:R.find(U=>U.label===m)??void 0;D.mutate({client:K,path:{name:t},body:{queries:L,...r?{provider:r}:{},...r&&i.trim()?{model:i.trim()}:{},...N!==void 0?{location:N}:{}}})}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(he,{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:N=>a(N.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${L.length>50?"text-negative":"text-faint"}`,children:[L.length," ",L.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 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:r,onChange:N=>{o(N.target.value),u("")},children:[e.jsx("option",{value:"",children:"Project default"}),c.map(N=>e.jsx("option",{value:N.name,children:N.displayName??N.name},N.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:m,onChange:N=>d(N.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),R.map(N=>e.jsx("option",{value:N.label,children:N.label},N.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:i,disabled:!S,onChange:N=>u(N.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(S?.catalog.knownModels??[]).map(N=>e.jsx("option",{value:N.id,children:N.displayName},N.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!te()&&e.jsxs(We,{type:"button",size:"sm",disabled:L.length===0||L.length>50||v||D.isPending,onClick:T,children:[e.jsx(ia,{size:14}),D.isPending?"Starting research…":`Run ${L.length||""} research ${L.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),v&&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(he,{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"})]}),g.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),f.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:f.map(N=>e.jsxs("tr",{className:p===N.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>h(N.id),children:tx(N.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:N.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:N.requestedModel??N.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:N.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[N.completedQueries+N.failedQueries,"/",N.totalQueries]}),e.jsx("td",{children:e.jsx(de,{tone:Mo(N.status),children:N.status})})]},N.id))})]})})]})]}),e.jsx(Xh,{detail:z,isLoading:C.isFetching})]})}function Xh({detail:t,isLoading:s}){const[n,a]=l.useState(null);l.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const r=t?.queries.find(o=>o.id===n)??t?.queries[0]??null;return e.jsxs(he,{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 ${sx(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(de,{tone:Mo(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(o=>e.jsxs("tr",{className:r?.id===o.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(o.id),children:o.query})}),e.jsx("td",{children:e.jsx(de,{tone:nx(o.status),children:o.status})}),e.jsx("td",{children:e.jsx(de,{tone:o.answerMentioned===!0?"positive":o.answerMentioned===!1?"neutral":o.status===Js.failed?"negative":"caution",children:o.answerMentioned===null?o.status===Js.failed?"Unavailable":"Pending":o.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(de,{tone:o.citationState==="cited"?"positive":o.citationState==="not-cited"?"neutral":o.status===Js.failed?"negative":"caution",children:o.citationState===null?o.status===Js.failed?"Unavailable":"Pending":o.citationState==="cited"?"Cited":"Not cited"})})]},o.id))})]})}),e.jsx(Zh,{query:r,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 Zh({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===Js.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 r=zs(n.uri),o=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[r?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:o}):e.jsx("span",{className:"truncate text-secondary",children:o}),r&&e.jsx(ju,{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 ex(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 tx(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 sx(t){return t.length>8?t.slice(0,8):t}function Mo(t){return t===Rn.completed?"positive":t===Rn.partial?"caution":t===Rn.failed?"negative":"neutral"}function nx(t){return t===Js.completed?"positive":t===Js.failed?"negative":"neutral"}async function ax(t){await yt(t,"researchRuns")}const ar=new Set(["queued","seeding","probing"]);function rx({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(ix,{projectName:t}):e.jsx(Jh,{projectName:t})})]})}function ix({projectName:t}){const s=ks(),[n,a]=l.useState(null),[r,o]=l.useState(""),[i,u]=l.useState("100"),m=Re({...oc({client:K,path:{name:t},query:{limit:"10"}}),refetchInterval:c=>c.state.data?.some(S=>ar.has(S.status))?3e3:!1}),d=m.data??[];l.useEffect(()=>{!n&&d[0]&&a(d[0].id)},[n,d]);const p=d.find(c=>c.id===n)??null,h=Re({...lc({client:K,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&ar.has(p.status)?3e3:!1}),j=h.data??null,b=Re({...cc({client:K,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),g=Et({mutationFn:()=>{const c={},v=r.trim();v&&(c.icpDescription=v);const S=Number.parseInt(i,10);return Number.isFinite(S)&&S>0&&(c.maxProbes=S),dc(t,c)},onSuccess:async c=>{a(c.sessionId),o(""),await hi(s,t,c.sessionId),Ce({title:"Discovery started",detail:`Run ${Da(c.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${c.sessionId}`,dedupeMode:"replace"})},onError:c=>{Ce({title:"Discovery failed to start",detail:c instanceof Error?c.message:"Could not start discovery.",tone:"negative"})}}),f=Et({mutationFn:c=>{if(!n)throw new Error("Select a completed discovery session first.");return uc(t,n,c)},onSuccess:async c=>{await hi(s,t,c.sessionId),s.invalidateQueries({queryKey:to({client:K})}),s.invalidateQueries({predicate:v=>Array.isArray(v.queryKey)&&v.queryKey[0]==="projects"&&v.queryKey.length>1}),Ce({title:"Queries added",detail:dx(c),tone:"positive",dedupeKey:`discovery:promote:${c.sessionId}`,dedupeMode:"replace"})},onError:c=>{Ce({title:"Could not add queries",detail:c instanceof Error?c.message:"Could not add queries from this run.",tone:"negative"})}}),y=j??p,C=b.data??null,z=(C?.queriesByBucket.cited.length??0)+(C?.queriesByBucket.aspirational.length??0),L=l.useMemo(()=>(j?.probes??[]).slice(0,30),[j?.probes]);async function R(){try{const c=await m.refetch();if(c.error)throw c.error;const v=c.data?.length??0;Ce({title:"Discovery sessions refreshed",detail:`${v} recent session${v===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(c){Ce({title:"Discovery refresh failed",detail:c instanceof Error?c.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:te()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{R()},children:[e.jsx(ra,{className:`size-3.5 ${m.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(he,{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(de,{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:r,onChange:c=>o(c.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:i,onChange:c=>u(c.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!te()&&e.jsxs(We,{type:"button",size:"sm",disabled:g.isPending,onClick:()=>g.mutate(),children:[e.jsx(ia,{size:14}),g.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(he,{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"})]}),m.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),d.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:d.map(c=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===c.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(c.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:Da(c.id)}),e.jsx(de,{tone:mi(c.status),children:c.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",c.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",c.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",c.wastedCount??0]})]})]},c.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:y?Da(y.id):"No run selected"})]}),y&&e.jsx(de,{tone:mi(y.status),children:y.status})]}),y?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx($s,{label:"Questions tested",value:y.probeCount??0}),e.jsx($s,{label:"Cited queries",value:y.citedCount??0,tone:"positive"}),e.jsx($s,{label:"Worth tracking",value:y.aspirationalCount??0,tone:"caution"}),e.jsx($s,{label:"Skip",value:y.wastedCount??0,tone:"negative"})]}),y.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:y.error}),y.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:y.warning}),y.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:y.icpDescription})]}),y.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:y.competitorMap.slice(0,8).map(c=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[c.domain," ",e.jsx("span",{className:"text-muted",children:c.hits})]},c.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),y?.status==="completed"&&e.jsxs(he,{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"})]}),!te()&&e.jsxs(We,{type:"button",size:"sm",disabled:f.isPending||z===0,onClick:()=>f.mutate(void 0),children:[e.jsx(oo,{size:14}),f.isPending?"Adding…":"Add recommended queries"]})]}),b.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):C?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx($s,{label:"Queries to add",value:z,tone:"positive"}),e.jsx($s,{label:"Cited queries",value:C.queriesByBucket.cited.length,tone:"positive"}),e.jsx($s,{label:"Worth tracking",value:C.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx($s,{label:"Skip",value:C.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."}),C.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:C.suggestedCompetitors.map(c=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[c.domain," ",e.jsx("span",{className:"text-muted",children:c.hits})]},c.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),h.isFetching&&e.jsx(de,{tone:"neutral",children:"Loading"})]}),L.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:L.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:c.query}),e.jsx("td",{children:e.jsx(de,{tone:ox(c.bucket),children:cx(c.bucket)})}),e.jsx("td",{className:"text-secondary",children:c.citedDomains.length>0?c.citedDomains.slice(0,3).join(", "):"-"})]},c.id))})]})})]})]})]})]})}function $s({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 mi(t){return t==="completed"?"positive":t==="failed"?"negative":ar.has(t)?"caution":"neutral"}function ox(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const lx={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function cx(t){return t?lx[t]:"Not classified"}function Da(t){return t.length>8?t.slice(0,8):t}function dx(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 hi(t,s,n){await Promise.all([yt(t,"discovery"),t.invalidateQueries({queryKey:mc({client:K})})])}function xi(t){return`${(t*100).toFixed(1)}%`}function ux({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),u=Re({...hc({client:K,path:{name:t},query:{limit:30}}),enabled:s==="health"}),m=Re({...xc({client:K,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),d=(m.data??[]).filter(y=>(y.status==="completed"||y.status==="partial")&&y.trigger!=="probe").reverse(),p=o??d[0]?.id??"",h=a??d.find(y=>y.id!==p)?.id??"",j=!!(h&&p&&h!==p),b=Re({...pc({client:K,path:{name:t},query:{run1:h,run2:p}}),enabled:s==="compare"&&j}),g=u.data??[],f=b.data?.diff.filter(y=>y.changed||y.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(([y,C])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===y,className:`filter-chip ${s===y?"filter-chip-active":""}`,onClick:()=>n(y),children:C},y))}),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."})]}),u.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!u.isLoading&&g.length===0?e.jsxs(he,{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,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:"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:g.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(y.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[y.mentionedPairs,"/",y.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:xi(y.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[y.citedPairs,"/",y.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:xi(y.overallCitedRate)})]},y.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:h,onChange:y=>r(y.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:d.map(y=>e.jsx("option",{value:y.id,children:new Date(y.createdAt).toLocaleString()},y.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:p,onChange:y=>i(y.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:d.map(y=>e.jsx("option",{value:y.id,children:new Date(y.createdAt).toLocaleString()},y.id))})]})]}),m.isLoading||b.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!m.isLoading&&d.length<2?e.jsxs(he,{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,b.data&&f.length===0?e.jsxs(he,{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,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:f.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:y.query??"Archived query"}),e.jsx("td",{children:e.jsxs(de,{tone:y.changed?"caution":"neutral",children:[y.run1State??"none"," → ",y.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(de,{tone:y.visibilityChanged?"caution":"neutral",children:[y.run1MentionState??"none"," → ",y.run2MentionState??"none"]})})]},y.queryId??y.query??"unknown"))})]})}):null]}):null]})}const pi={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},mx={contract:null,assessment:null,googleAds:pi,gtm:pi,snapshots:[]};function hx(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":fx(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function xx(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 px(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 gx(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 Lo(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"&&bx(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 fx(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function bx(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Do(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 yx(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 vx(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 Us(t){return t.length<=12?t:`…${t.slice(-10)}`}function jx(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 Nx(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 Ea={"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 gi(t){return t.outcome==="pass"?{label:Ea[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Ea[t.code],tone:"negative",outcome:"Fail"}:{label:Ea[t.code],tone:"caution",outcome:"Unknown"}}function wx(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Sx(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 Cx(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function fi({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=Do(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(de,{tone:o.tone,children:o.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Bt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const kx="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.",Ax="Available once Google Ads and Tag Manager are connected.",Px="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 Rx({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",u=t.gtm.state==="connected",m=t.googleAds.state==="unavailable",d=t.gtm.state==="unavailable",p=m||d||t.gtm.state==="unavailable",h={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},j=!i&&!u,b=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:m?h:px(t)},{title:"Tag Manager",state:t.gtm.state,ready:u,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:d?h:gx(t)}],g=i&&u&&!p?Lo(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(ze,{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."})]}),j?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Px}):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(ze,{text:kx})]}),g&&s?e.jsx(We,{type:"button",disabled:r,onClick:()=>s(g.id),children:r?"Working…":g.label}):e.jsx("p",{className:"text-sm text-secondary",children:Ax})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:b.map(f=>{const y=f.ready?{label:"Ready",tone:"positive"}:Do(f.state),C=f.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:f.title}),e.jsx(de,{tone:y.tone,children:y.label}),f.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:f.summary}):null,C&&s?C.id==="retry-connection-status"?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):null,f.summary&&f.onChange?e.jsx(We,{type:"button",variant:"ghost",size:"sm","aria-label":f.changeLabel,disabled:r,onClick:f.onChange,children:"Change"}):null]},f.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Ix({workspace:t=mx,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:u=null,onRetryContracts:m,onRetryEvidence:d,onChangeGoogleAdsSelection:p,onChangeGtmSelection:h,onAddContract:j}){const b=hx(t),g=xx(b),f=Lo(t),y=t.assessment?.findings??[],C=y.filter(c=>c.outcome!=="pass"),z=y.filter(c=>c.outcome==="pass"),L=C.some(c=>c.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&u===null?e.jsx(Rx,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:p,onChangeGtmSelection:h,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(de,{tone:g.tone,children:g.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Bt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:g.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(c=>e.jsxs("li",{className:"break-words",children:[Cx(c)," ",c.kind,", captured ",Bt(c.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",c.id,")"]})]},c.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?f.id==="review-findings"||f.id==="review-runtime-verification"||f.id==="retry-connection-status"||f.id==="select-contract"||f.id==="retry-integrity"||f.id==="waiting-for-integrity"?e.jsx(A,{type:"button",disabled:n||f.id==="waiting-for-integrity",onClick:()=>s(f.id),children:n?"Working…":f.label}):e.jsx(We,{type:"button",disabled:n,onClick:()=>s(f.id),children:n?"Working…":f.label}):f.id==="review-findings"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):b==="runtime-unverified"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:f.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&j?e.jsx(We,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:j,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:o??"",onChange:c=>i?.(c.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(c=>e.jsx("option",{value:c.id,children:c.name},c.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:jx(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:Nx(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:Us(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:Us(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:Us(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:Us(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."}),u?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:u}),m?e.jsx(A,{type:"button",variant:"outline",onClick:m,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),C.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(de,{tone:L,children:[C.length," ",C.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:C.map(c=>{const v=gi(c);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(de,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",c.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",c.code]}),c.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",c.evidenceIds.join(", ")]}):null]},`${c.code}:${c.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(ze,{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(c=>{const v=yx(c.key,b);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:c.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:c.detail}),e.jsx(de,{tone:v,children:vx(c.key,b)})]},c.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:[fi({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:p}:{},actionPending:n}),fi({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:h}:{},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)&&d?e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:d,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(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:c.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:c.kind}),e.jsx("td",{className:"text-secondary",children:Bt(c.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:Us(c.id)})]},c.id))})]})})]}):null,z.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[z.length," ",z.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:z.map(c=>{const v=gi(c);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",c.code]}),c.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",c.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(de,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:c.subject})]},`${c.code}:${c.subject}`)})})]})})]}):null,b==="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 ",wx(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:Us(t.contract.gtm.tagId)})," fires with ",Sx(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:Us(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Bs=3e4,bi={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Rt="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",ts="text-sm font-medium text-secondary";function yi(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:mt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function zn(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function $x(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Google Ads connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Google Ads OAuth connection is stored for this project.",lastSnapshotAt:null};if(t.status==="selection-required"){const r=t.connection.selection.customerId;return r?{state:"stale",selection:`Selected customer ${r}`,...s,evidence:"A customer is selected, but Canonry needs a fresh conversion-goal observation.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}:{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs a customer account selection.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}const a=t.selectedCustomer;return{state:t.status,selection:a.descriptiveName??`Selected customer ${a.customerId}`,...s,evidence:t.status==="stale"?"The selected customer needs a fresh conversion-goal observation.":"Selected customer and conversion-goal evidence are stored.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}function Tx(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Mx(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:Tx(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 Lx(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:zn(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:zn(t.triggerIds),variableIds:zn(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:zn(t.productionHosts)}}}function vi(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function Qn(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 Hn(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Wn({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:ts,children:[s,e.jsx("select",{id:t,className:Rt,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function un({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function ji({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[u,m]=l.useState(null),d=l.useRef(null),p=l.useRef(null),h=l.useRef(!1);l.useEffect(()=>{const f=h.current;h.current=a,a?p.current?.focus():f&&d.current?.querySelector("button")?.focus()},[a]);function j(){m(null),r(!0)}function b(){m(null),r(!1)}async function g(){i(!0),m(null);try{await n()}catch(f){m(mt(f)),i(!1)}}return e.jsx("div",{ref:d,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(A,{ref:p,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:b,children:"Keep connected"}),e.jsx(We,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{g()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),u?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:u}):null]}):e.jsxs(We,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:j,children:["Disconnect ",t]})})}function Ni({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:u,value:m,onChange:d}){const p=n.some(f=>f.id===m),[h,j]=l.useState(!1),b=h||m!==""&&!p&&n.length>0,g=e.jsx("label",{htmlFor:t,className:ts,children:s});return r?e.jsxs("div",{children:[g,e.jsx("select",{id:t,className:Rt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[g,e.jsx("input",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[g,e.jsx("input",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":u})]}):e.jsxs("div",{children:[g,b?e.jsx("input",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value)}):e.jsxs("select",{id:t,required:!0,className:Rt,value:m,onChange:f=>d(f.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(f=>e.jsxs("option",{value:f.id,children:[f.name,f.detail?` (${f.detail})`:"",f.active?"":" — inactive"]},f.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{j(!b),d("")},children:b?"Choose from synced list":"Enter an ID manually"})]})}function Dx({projectId:t,projectName:s}){const n=so(),[a,r]=l.useState(null),[o,i]=l.useState(null),[u,m]=l.useState(!1),[d,p]=l.useState(""),[h,j]=l.useState(null),[b,g]=l.useState(!1),[f,y]=l.useState(!1),[C,z]=l.useState(""),[L,R]=l.useState(""),[c,v]=l.useState(""),[S,D]=l.useState(""),[T,N]=l.useState(""),[U,E]=l.useState(!1),[B,H]=l.useState(bi),[ge,ke]=l.useState(null),_=l.useRef(null),se=Re({...gc({client:K,path:{name:s}}),staleTime:Bs}),re=Re({...fc({client:K,path:{name:s}}),staleTime:Bs}),X=Re({...bc({client:K,path:{name:s}}),staleTime:Bs}),Q=Re({...yc({client:K,path:{name:s}}),staleTime:Bs}),P=Q.data,G=Re({...vc({client:K,path:{name:s},query:{limit:5}}),staleTime:Bs}),Y=Re({...jc({client:K,path:{name:s},query:{limit:5}}),staleTime:Bs}),J=X.data??[],xe=(ge?J.find(w=>w.id===ge)??null:null)??(J.length===1?J[0]??null:null),V=J.length>1&&!xe,le=Re({...Nc({client:K,path:{name:s,contractId:xe?.id??""}}),enabled:!!xe,staleTime:Bs}),je=Re({...wc({client:K,path:{name:s}}),enabled:h==="google-ads"&&se.data?.connected===!0,staleTime:0}),Fe=Re({...Sc({client:K,path:{name:s}}),enabled:h==="gtm"&&re.data?.connected===!0,staleTime:0}),Le=Re({...Cc({client:K,path:{name:s,accountId:c}}),enabled:h==="gtm"&&!!c,staleTime:0}),Ae=Re({...kc({client:K,path:{name:s,accountId:c,containerId:S}}),enabled:h==="gtm"&&!!c&&!!S,staleTime:0}),Xe=Et(Ac({client:K})),lt=Et(Pc({client:K})),we=Et(Rc({client:K})),et=Et(Ic({client:K})),Ve=Et($c({client:K})),_e=Et(Tc({client:K})),Ue=Et(Mc({client:K})),Ie=Et(Lc({client:K})),F=Et(Dc({client:K}));l.useEffect(()=>{if(h!=="google-ads"||b||!se.isSuccess)return;const w=se.data.connection?.selection;z(w?.customerId??""),R(w?.loginCustomerId??""),g(!0)},[b,se.data,se.isSuccess,h]),l.useEffect(()=>{if(h!=="gtm"||f||!re.isSuccess)return;const w=re.data.selection;v(w?.accountId??""),D(w?.containerId??""),N(w?.workspaceId??""),y(!0)},[f,re.data,re.isSuccess,h]),l.useEffect(()=>{!ge||!X.data||X.data.some(w=>w.id===ge)||ke(null)},[X.data,ge]);const $=l.useMemo(()=>{const w=G.data?.snapshots??[],oe=Y.data?.snapshots??[],at=[...w.map(Tt=>({id:Tt.id,provider:"google-ads",kind:Tt.kind,capturedAt:Tt.capturedAt})),...oe.map(Tt=>({id:Tt.id,provider:"gtm",kind:Tt.kind,capturedAt:Tt.capturedAt}))].sort((Tt,Ft)=>Ft.capturedAt.localeCompare(Tt.capturedAt)).slice(0,5),Pe=[],it=le.data?.googleAdsSnapshot,Jt=le.data?.gtmSnapshot;return it&&Pe.push({id:it.id,provider:"google-ads",kind:it.kind,capturedAt:it.capturedAt}),Jt&&Pe.push({id:Jt.id,provider:"gtm",kind:Jt.kind,capturedAt:Jt.capturedAt}),{contract:le.data?.assessment.contract??xe,assessment:le.data?.assessment??null,contractSelectionRequired:V,assessmentState:xe?le.isError?"unavailable":le.isLoading?"loading":void 0:void 0,assessmentError:le.isError?mt(le.error):null,googleAds:$x(se.data,yi(G.data?.total??0,G.isLoading,G.isError,G.error),se.isError),gtm:Mx(re.data,yi(Y.data?.total??0,Y.isLoading,Y.isError,Y.error),re.isError),snapshots:at,assessmentEvidenceSnapshots:Pe}},[xe,V,G.data,G.error,G.isError,G.isLoading,se.data,se.isError,Y.data,Y.error,Y.isError,Y.isLoading,re.data,re.isError,le.data,le.error,le.isError,le.isLoading]),q=l.useSyncExternalStore(Xi,sa,sa),me=Object.values(q.runs).some(w=>w.projectId===t&&(w.kind===Gs["google-ads-sync"]||w.kind===Gs["gtm-sync"])),fe=Xe.isPending||lt.isPending||we.isPending||et.isPending||Ve.isPending||_e.isPending||Ue.isPending||Ie.isPending||F.isPending||me;async function Z(){await Promise.all([se.refetch(),re.refetch(),X.refetch(),G.refetch(),Y.refetch(),Q.refetch(),xe?le.refetch():Promise.resolve()])}async function Ze(w){await Z();for(let oe=0;oe<10&&!w();oe+=1)await new Promise(at=>setTimeout(at,1500)),await Z()}function Kt(){const w=document.activeElement;_.current=w instanceof HTMLElement?w:null}function Ye(w){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(w);return}globalThis.setTimeout(w,0)}function $e(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Te(w){if(!w)return;!w.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!w.hasAttribute("tabindex")&&(w.tabIndex=-1),w.focus({preventScroll:!0})}function pt(w,oe=w){const at=document.getElementById(w);at instanceof HTMLDetailsElement&&(at.open=!0);const Pe=at?.scrollIntoView;typeof Pe=="function"&&Pe.call(at,{behavior:$e()?"auto":"smooth",block:"start"}),Te(document.getElementById(oe)??at)}function ct(w,oe){Kt(),Ye(()=>pt(w,oe))}function Oe(){const w=_.current;_.current=null,w&&Ye(()=>{w.isConnected&&w.focus({preventScroll:!0})})}function Qe(){r(null),m(!1),Oe()}function vt(){r(null),j(null),Oe()}function Ke(){r(null),E(!1),Oe()}function Ee(){r(null),j(null),m(!0),ct("google-ads-connect-panel","google-ads-connect-title")}function qe(){r(null),z(""),R(""),g(!1),j("google-ads"),m(!1),ct("google-ads-selection-panel","google-ads-selection-title")}function jt(){r(null),v(""),D(""),N(""),y(!1),j("gtm"),m(!1),ct("gtm-selection-panel","gtm-selection-title")}function Ge(){r(null),E(!0),ct("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function It(w,oe){Ji({id:w.id,projectId:w.projectId,kind:w.kind,projectLabel:s,sourceAction:oe}),Ce({title:oe==="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:${w.id}`,dedupeMode:"replace"})}async function Gt(){ps(n),r(null);try{const w=await Xe.mutateAsync({path:{name:s},body:{provider:"google-ads",...d.trim()?{developerToken:d.trim()}:{}}});p(""),m(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),vi(w.authorizationUrl,()=>{Z(),i(null),Oe()})}catch(w){r(mt(w))}}async function gt(){ps(n),r(null);try{const w=await lt.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),vi(w.authorizationUrl,()=>{Z(),i(null),Oe()})}catch(w){r(mt(w))}}async function kt(){if(ps(n),!C){r("Select a Google Ads customer before saving.");return}r(null);try{await we.mutateAsync({path:{name:s},body:{customerId:C,...L.trim()?{loginCustomerId:L.trim()}:{}}}),j(null),Oe(),await Ze(()=>se.data?.selectedCustomer!=null)}catch(w){r(mt(w))}}async function ht(){if(ps(n),!c||!S){r("Select a Tag Manager account and container before saving.");return}r(null);try{await et.mutateAsync({path:{name:s},body:{accountId:c,containerId:S,...T?{workspaceId:T}:{}}}),j(null),Oe(),await Ze(()=>re.data?.status==="connected")}catch(w){r(mt(w))}}async function O(){ps(n),r(null),await Ue.mutateAsync({path:{name:s}}),j(null),m(!1),z(""),R(""),g(!1),i(null),await Z(),Ce({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),_.current=null,Ye(()=>Te(document.getElementById("conversion-integrity-title")))}async function Se(){ps(n),r(null),await Ie.mutateAsync({path:{name:s}}),j(null),v(""),D(""),N(""),y(!1),i(null),await Z(),Ce({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),_.current=null,Ye(()=>Te(document.getElementById("conversion-integrity-title")))}async function be(){ps(n),r(null);try{const w=await Ve.mutateAsync({path:{name:s}});It(w,"google-ads-sync")}catch(w){r(mt(w))}}async function ve(){ps(n),r(null);try{const w=await _e.mutateAsync({path:{name:s}});It(w,"gtm-sync")}catch(w){r(mt(w))}}async function ft(){ps(n),r(null);try{const w=await Promise.allSettled([Ve.mutateAsync({path:{name:s}}),_e.mutateAsync({path:{name:s}})]),[oe,at]=w;oe.status==="fulfilled"&&It(oe.value,"google-ads-sync"),at.status==="fulfilled"&&It(at.value,"gtm-sync");const Pe=w.find(it=>it.status==="rejected");if(Pe?.status==="rejected")throw Pe.reason}catch(w){r(mt(w))}}async function Je(){ps(n);const w=se.data?.connection?.selection.customerId,oe=re.data?.selection;if(!w||!oe?.accountId||!oe.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const at=await F.mutateAsync({path:{name:s},body:Lx(B,w,{accountId:oe.accountId,containerId:oe.containerId})});H(bi),E(!1),Oe(),(await X.refetch()).data?.some(it=>it.id===at.id)&&ke(at.id)}catch(at){r(mt(at))}}function At(w){switch(w){case"connect-google-ads":Ee();return;case"connect-gtm":Kt(),gt();return;case"select-google-ads":qe();return;case"select-gtm":jt();return;case"sync-google-ads":be();return;case"sync-gtm":ve();return;case"sync-static-evidence":ft();return;case"declare-contract":Ge();return;case"review-findings":ct("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":ct("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Z();return;case"select-contract":ct("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":le.refetch();return;case"waiting-for-integrity":return}}const Nt=je.data?.customers??[],rs=Fe.data?.accounts??[],is=Le.data?.containers??[],cs=Ae.data?.workspaces??[],rt=!!C&&!Nt.some(w=>w.customerId===C),ds=!!c&&!rs.some(w=>w.id===c),dt=!!S&&!is.some(w=>w.id===S),bs=!!T&&!cs.some(w=>w.id===T),Wt=rt&&je.isSuccess&&je.data.truncated===!1,zt=ds&&Fe.isSuccess&&Fe.data.truncated===!1,Yt=dt&&Le.isSuccess&&Le.data.truncated===!1,wt=bs&&Ae.isSuccess&&Ae.data.truncated===!1,us=zt||Yt||wt,Qt=zt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Yt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":wt?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,bt=Hn(Wt,je.data,je.isError),ys=Hn(zt,Fe.data,Fe.isError),Pt=Hn(Yt,Le.data,Le.isError),ms=Hn(wt,Ae.data,Ae.isError),hs=je.isError?mt(je.error):null,xs=Fe.isError?mt(Fe.error):Le.isError?mt(Le.error):Ae.isError?mt(Ae.error):null,St=h==="google-ads"?hs:h==="gtm"?xs:null,I=Qn("customer",je.data,Nt.length),ee=Qn("account",Fe.data,rs.length),pe=Qn("container",Le.data,is.length),ne=Qn("draft workspace",Ae.data,cs.length),ie=Fe.isError||Le.isError||Ae.isError&&!!T,Me=u||h!==null||U;function $t(){je.refetch()}function ut(){if(Fe.isError){Fe.refetch();return}if(Le.isError){Le.refetch();return}Ae.isError&&Ae.refetch()}return se.isLoading||re.isLoading||X.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(w=>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"})]},w))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):X.isError&&!X.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",mt(X.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{X.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ix,{workspace:$,onPrimaryAction:At,actionPending:fe,actionError:Me?null:a,contracts:J,selectedContractId:xe?.id??null,onSelectContract:w=>ke(w||null),contractError:X.isError?mt(X.error):null,onRetryContracts:()=>{X.refetch()},onRetryEvidence:()=>{Promise.all([G.refetch(),Y.refetch()])},onChangeGoogleAdsSelection:qe,onChangeGtmSelection:jt,onAddContract:()=>At("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,u?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:De(async w=>{w.preventDefault(),await Gt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ts,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:d,onChange:w=>p(w.target.value),className:Rt,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(We,{type:"submit",disabled:Xe.isPending,children:Xe.isPending?"Starting…":"Continue to Google"}),e.jsx(A,{type:"button",variant:"outline",onClick:Qe,children:"Cancel"})]})]})]}):null,h==="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"})]})}),St?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:St}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:$t,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Wt?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(Wn,{id:"google-ads-customer",label:"Customer account",value:C,onChange:w=>{g(!0),z(w);const oe=Nt.find(at=>at.customerId===w);R(oe?.parentCustomerId??"")},disabled:je.isLoading,children:[e.jsx("option",{value:"",children:je.isLoading?"Loading accessible customers…":"Select a customer"}),rt?e.jsxs("option",{value:C,disabled:Wt,children:["Saved customer ",C," (",bt,")"]}):null,Nt.map(w=>e.jsx("option",{value:w.customerId,children:w.descriptiveName??`Customer ${w.customerId}`},w.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ts,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Rt,value:L,onChange:w=>{g(!0),R(w.target.value)},placeholder:"Use only when a manager context is required"})]})]}),I?e.jsx("p",{role:"status",className:`mt-3 text-sm ${je.data?.truncated?"text-caution":"text-secondary"}`,children:I}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:we.isPending||je.isLoading||je.isError||Wt||!C,onClick:De(kt),children:we.isPending?"Saving…":"Save customer selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:vt,children:"Cancel"})]}),se.data?.connected?e.jsx(ji,{providerLabel:"Google Ads",disabled:fe,onDisconnect:O}):null]}):null,h==="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"})]})}),St?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:St}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:ut,children:Fe.isError?"Retry account list":Le.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Qt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Qt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Wn,{id:"gtm-account",label:"Account",value:c,onChange:w=>{y(!0),w!==c&&(D(""),N("")),v(w)},disabled:Fe.isLoading,children:[e.jsx("option",{value:"",children:Fe.isLoading?"Loading accounts…":"Select an account"}),ds?e.jsxs("option",{value:c,disabled:zt,children:["Saved account ",c," (",ys,")"]}):null,rs.map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]}),e.jsxs(Wn,{id:"gtm-container",label:"Container",value:S,onChange:w=>{y(!0),w!==S&&N(""),D(w)},disabled:!c||Le.isLoading,children:[e.jsx("option",{value:"",children:Le.isLoading?"Loading containers…":"Select a container"}),dt?e.jsxs("option",{value:S,disabled:Yt,children:["Saved container ",S," (",Pt,")"]}):null,is.map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]}),e.jsxs(Wn,{id:"gtm-workspace",label:"Draft workspace (optional)",value:T,onChange:w=>{y(!0),N(w)},disabled:!S||Ae.isLoading,children:[e.jsx("option",{value:"",children:Ae.isLoading?"Loading workspaces…":"No draft workspace"}),bs?e.jsxs("option",{value:T,disabled:wt,children:["Saved draft workspace ",T," (",ms,")"]}):null,cs.map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[ee?e.jsx("p",{role:"status",className:Fe.data?.truncated?"text-caution":"text-secondary",children:ee}):null,pe?e.jsx("p",{role:"status",className:Le.data?.truncated?"text-caution":"text-secondary",children:pe}):null,ne?e.jsx("p",{role:"status",className:Ae.data?.truncated?"text-caution":"text-secondary",children:ne}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(We,{type:"button",disabled:et.isPending||Fe.isLoading||Le.isLoading||Ae.isLoading&&!!T||ie||us||!c||!S,onClick:De(ht),children:et.isPending?"Saving…":"Save container selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:vt,children:"Cancel"})]}),re.data?.connected?e.jsx(ji,{providerLabel:"Tag Manager",disabled:fe,onDisconnect:Se}):null]}):null,U?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:De(async w=>{w.preventDefault(),await Je()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ts,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Rt,value:B.name,onChange:w=>H(oe=>({...oe,name:w.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ts,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Rt,value:B.eventName,onChange:w=>H(oe=>({...oe,eventName:w.target.value})),placeholder:"booking_complete"})]}),e.jsx(Ni,{id:"contract-conversion-action",label:"Google Ads conversion action",options:P?.googleAds.conversionActions??[],synced:P?.googleAds.syncedAt!=null,loading:Q.isLoading,failed:Q.isError,onRetry:()=>{Q.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:B.conversionActionId,onChange:w=>H(oe=>({...oe,conversionActionId:w}))}),e.jsx(Ni,{id:"contract-gtm-tag",label:"Tag Manager tag",options:P?.gtm.tags??[],synced:P?.gtm.syncedAt!=null,loading:Q.isLoading,failed:Q.isError,onRetry:()=>{Q.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:B.tagId,onChange:w=>H(oe=>({...oe,tagId:w}))})]}),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:ts,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Rt,value:B.conversionId,onChange:w=>H(oe=>({...oe,conversionId:w.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ts,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Rt,value:B.conversionLabel,onChange:w=>H(oe=>({...oe,conversionLabel:w.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ts,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Rt,value:B.triggerIds,onChange:w=>H(oe=>({...oe,triggerIds:w.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ts,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Rt,value:B.variableIds,onChange:w=>H(oe=>({...oe,variableIds:w.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ts,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Rt,value:B.campaignIds,onChange:w=>H(oe=>({...oe,campaignIds:w.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ts,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Rt,value:B.productionHosts,onChange:w=>H(oe=>({...oe,productionHosts:w.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(un,{id:"contract-primary-action",checked:B.requirePrimaryAction,onChange:w=>H(oe=>({...oe,requirePrimaryAction:w})),children:"Google Ads action is primary"}),e.jsx(un,{id:"contract-biddable-goal",checked:B.requireBiddableGoal,onChange:w=>H(oe=>({...oe,requireBiddableGoal:w})),children:"Google Ads goal is biddable"}),e.jsx(un,{id:"contract-runtime-verification",checked:B.verificationRequired,onChange:w=>H(oe=>({...oe,verificationRequired:w})),children:"Runtime proof is required"}),e.jsx(un,{id:"contract-transaction-id",checked:B.requireTransactionId,onChange:w=>H(oe=>({...oe,requireTransactionId:w})),children:"Transaction ID is required"}),e.jsx(un,{id:"contract-value",checked:B.requireValue,onChange:w=>H(oe=>({...oe,requireValue:w})),children:"Conversion value is required"}),e.jsx(un,{id:"contract-currency",checked:B.requireCurrency,onChange:w=>H(oe=>({...oe,requireCurrency:w})),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(We,{type:"submit",disabled:F.isPending,children:F.isPending?"Saving…":"Save conversion contract"}),e.jsx(A,{type:"button",variant:"outline",onClick:Ke,children:"Cancel"})]})]})]}):null]})}const Ex=6e4,qx=["7d","14d","30d"],mr="not available",Ox='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%.',Gx="No Google Ads snapshot stored yet",Fx="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.",_x="No closed days yet",Ux="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.",Bx={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Ts=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),qa=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Eo=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),Vx=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function mn(t,s){return t===null||!Number.isFinite(t)?mr:s===null?Vx.format(t/1e6):Vu(t,s)}function Oa(t){if(t===null||!Number.isFinite(t))return mr;const s=t*100;return s>0&&s<.1?"<0.1%":`${Eo.format(s)}%`}function Kx(t,s){if(t===null||!Number.isFinite(t))return`${mr} 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%":`${Eo.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function zx(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Qx(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 Wx({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=Re({...Ec({client:K,path:{name:t},query:{window:s}}),staleTime:Ex}),i=o.data,u=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(ze,{text:Ox})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Ot(i.startDate)," to ",Ot(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(pa,{windows:qx,value:s,onChange:n,label:"Google Ads time period"})]});if(o.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[u,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(c=>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"})]},c))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(o.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[u,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",mt(o.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:m,daily:d,campaigns:p,comparison:h,comparisonUnavailableReason:j,source:b}=i;if(!b){const c=j==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[u,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:c?_x:Gx}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:c?Ux:Fx})]})]})}const g=b.currencyCode,f=b.campaignsInInventory>0&&b.campaignsQueried<b.campaignsInInventory?{queried:b.campaignsQueried,inInventory:b.campaignsInInventory}:null,y=m.costMicros>0&&m.conversions===0,C=[{key:"spend",comparable:!0,label:"Spend",value:mn(m.costMicros,g),change:h?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:qa.format(m.conversions),change:h?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:y?"no conversions":mn(m.costPerConversionMicros,g),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Oa(m.conversionRate),change:h?.change.conversionRate??null,direction:"up-good",seriesKey:null}],z=[{key:"clicks",label:"Clicks",value:Ts.format(m.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Ts.format(m.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Oa(m.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:mn(m.cpcMicros,g),seriesKey:null}],L={costMicros:{label:"Spend",color:nt[1],axisId:"spend",formatValue:c=>mn(c,g)},conversions:{label:"Conversions",color:nt[0],axisId:"conversions",formatValue:c=>qa.format(c)},clicks:{label:"Clicks",color:nt[2],axisId:"clicks",formatValue:c=>Ts.format(c)},impressions:{label:"Impressions",color:nt[3],axisId:"impressions",formatValue:c=>Ts.format(c)}},R=[...a].map(c=>({dataKey:c,...L[c]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[u,f!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Ts.format(f.queried)," of"," ",Ts.format(f.inInventory)," campaigns, so they are a subset of the account."]}):null,b.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,!h&&j==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:Bx["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:C.map(c=>{const v=c.seriesKey!==null&&a.has(c.seriesKey),S=v&&a.size===1,D=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[c.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?L[c.seriesKey].color:"var(--color-mono-600)"}}):null,c.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:c.value}),h&&c.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Hx(c.change,c.direction)}`,children:Kx(c.change,h.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:c.comparable?`no prior ${s} period stored`:" "})]});return c.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:D},c.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(T=>{const N=new Set(T);return N.has(c.seriesKey)?N.delete(c.seriesKey):N.add(c.seriesKey),N.size===0?T:N}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:D},c.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:z.map(c=>{const v=c.seriesKey!==null&&a.has(c.seriesKey),S=v&&a.size===1,D=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[c.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?L[c.seriesKey].color:"var(--color-mono-600)"}}):null,c.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:c.value})]});return c.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:D},c.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(T=>{const N=new Set(T);return N.has(c.seriesKey)?N.delete(c.seriesKey):N.add(c.seriesKey),N.size===0?T:N}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:D},c.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(co,{data:d,xKey:"date",series:R,xTickFormatter:tn,labelFormatter:Ot}),e.jsx("ul",{className:"sr-only",children:d.map(c=>e.jsxs("li",{children:[Ot(c.date),":"," ",R.map(v=>`${v.label} ${L[v.dataKey].formatValue(c[v.dataKey])}`).join(", "),c.origin==="filled"?", no delivery reported":""]},c.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(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:c.name??c.campaignId,children:c.name??e.jsx("span",{className:"font-mono text-secondary",children:c.campaignId})}),e.jsx("td",{children:e.jsx(de,{tone:zx(c.status),children:Qx(c.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ts.format(c.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ts.format(c.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:mn(c.totals.costMicros,g)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:qa.format(c.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Oa(c.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:c.totals.costMicros>0&&c.totals.conversions===0?e.jsx(de,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:mn(c.totals.costPerConversionMicros,g)})})]},c.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",qs(Cs(b.capturedAt))," · ","customer ",b.customerId," · ","latest closed day ",Ot(b.asOfDate),b.openDate?e.jsxs(e.Fragment,{children:[" · ",Ot(b.openDate)," still open, excluded"]}):null,b.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",b.timeZone]}):null]})]})]})}const Ga=20,ws=50,Yx=50,Jx=50;function hr(t){return t==="viewer"}function xr(t){return t?.status==="unavailable"}function qo(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Oo(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function Yn(t,s,n){if(t.kind==="all")return s.map(o=>o.id);if(t.kind==="specific")return s.filter(o=>t.propertyIds.includes(o.id)).map(o=>o.id);const a=new Set(t.groupIds),r=new Set(n.filter(o=>a.has(o.id)).flatMap(o=>o.propertyIds));return s.filter(o=>r.has(o.id)).map(o=>o.id)}function Xx(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(r=>s.find(o=>o.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function Fa(t,s){const n=new Set(s.map(r=>r.id)),a=t.propertyIds.filter(r=>n.has(r)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function wi(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Si(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 Jn(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 rr(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function _a(t){return rr(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ir({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[u,m]=l.useState(!1),d=o.trim().toLocaleLowerCase(),p=d?t.filter(g=>g.label.toLocaleLowerCase().includes(d)):t,h=u?p:p.slice(0,Yx),j=h.length<p.length;function b(){const g=new Set([...s,...h.map(f=>f.id)]);n(t.filter(f=>g.has(f.id)).map(f=>f.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:o,onChange:g=>i(g.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h.length===0,onClick:b,children:"Select all shown"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),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 ",h.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:h.map(g=>{const f=s.includes(g.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 ${g.label}`,checked:f,type:"checkbox",onChange:y=>n(qo(s,g.id,y.currentTarget.checked))}),e.jsx("span",{children:g.label})]}),g.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[g.urlCount," URLs"]})]},g.id)})}),j?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>m(!0),children:"Show all Properties"}):null]})]})}function pr(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(de,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function gr({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{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 Zx({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),u=t.preview,m=u?.counts.needsAttention??0,d=u?.rows.filter(S=>S.status==="matched")??[],p=u?.rows??[],h=p.filter(S=>S.status!=="matched"),j=Math.max(1,Math.ceil(p.length/ws)),b=Math.min(s,j-1),g=p.slice(b*ws,(b+1)*ws),f=Math.max(1,Math.ceil(h.length/ws)),y=Math.min(a,f-1),C=h.slice(y*ws,(y+1)*ws),z=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,L=d.length>0&&!t.isApplying,R=u!==null&&o===u.previewChecksum,c=h.length>0&&y===f-1;l.useEffect(()=>{n(0),r(0),i(null)},[u?.previewChecksum]);async function v(S){if(S)try{t.onCsvChange(await S.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:S=>{v(S.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:S=>t.onCsvChange(S.currentTarget.value),placeholder:`property,group,url
|
|
4
|
+
Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!z,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]}),u?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:[u.counts.matchedRows," matched · ",u.counts.groupsReady," group",u.counts.groupsReady===1?"":"s"," ready",m>0?` · ${m} need${m===1?"s":""} attention`:""]}),u.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:u.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,u.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 (",u.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:g.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(de,{tone:wi(S.status),children:Si(S.status)}),Jn(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Jn(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 ",b+1," of ",j," · ",u.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===j-1,onClick:()=>n(S=>Math.min(j-1,S+1)),children:"Next 50 rows"})]})]}):null,m>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 ",m," row",m===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:C.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(de,{tone:wi(S.status),children:Si(S.status)}),Jn(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Jn(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 ",y+1," of ",f]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:y===0,onClick:()=>r(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:y===f-1,onClick:()=>r(S=>Math.min(f-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:R,disabled:t.isApplying||!c,onChange:S=>i(S.currentTarget.checked?u.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",m," row",m===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!L||!R,onClick:()=>{t.onApply(d.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${d.length} matched row${d.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!L,onClick:()=>{t.onApply(d.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${u.counts.groupsReady} group${u.counts.groupsReady===1?"":"s"} with ${d.length} membership${d.length===1?"":"s"}`})]}):null]})}const ep="—";function tp({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:u=!0,onSelectedQueryIdsChange:m,onApplySelectedQueries:d,onClearQueryAssignments:p,onRemoveQuery:h,onCreateQueries:j,onCreateAndPairQuestions:b,isCreatingQueries:g=!1,createQueriesError:f=null,onManageProjectQueries:y,groups:C,audience:z,onAudienceChange:L,assignmentImpact:R=null,isPreviewingAssignmentImpact:c=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:S,assignmentNotice:D=null,onReplaceAssignments:T,isReplacingAssignments:N=!1,onBack:U,onContinue:E}){const[B,H]=l.useState(""),[ge,ke]=l.useState(!1),[_,se]=l.useState(!1),[re,X]=l.useState(""),[Q,P]=l.useState(""),[G,Y]=l.useState(null);if(xr(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(gr,{message:s.message})});const J=hr(t),W=z,xe=L,V=Yn(W,n,C),le=V.length,je=le>0&&r.length>0&&!o&&!i&&!c&&R!==null&&v===null,Fe=p??h,Le=B.trim().toLocaleLowerCase(),Ae=Le?a.filter(q=>_a(q).toLocaleLowerCase().includes(Le)):a,Xe=Ae.filter(q=>(q.propertyIds?.length??0)===0),lt=_?Xe:Ae,we=ge?lt:lt.slice(0,Jx),et=we.filter(q=>!rr(q)),Ve=[...new Set(re.split(`
|
|
5
|
+
`).map(q=>q.trim()).filter(Boolean))],_e=[...Q.matchAll(/\{([a-z][\w-]*)\}/gi)].map(q=>q[1]),Ue=n.filter(q=>V.includes(q.id)),Ie=_e.length===0||Q.trim()===""?[]:Ue.map(q=>({propertyId:q.id,text:_e.reduce((me,fe)=>me.replaceAll(`{${fe}}`,q.label),Q.trim())})),F=[...new Set(Ie.map(q=>q.text))];function $(){const q=new Set([...r,...et.map(me=>me.id)]);m(a.filter(me=>q.has(me.id)).map(me=>me.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."})]})}),J?e.jsx(pr,{}):null,J?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:W.kind==="all"?"all":W.kind==="specific"?"specific":`group:${W.groupIds[0]??""}`,onChange:q=>{const me=q.currentTarget.value;me==="all"?xe({kind:"all"}):me==="specific"?xe({kind:"specific",propertyIds:[]}):me.startsWith("group:")&&xe({kind:"groups",groupIds:[me.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]}),C.length>0?e.jsx("optgroup",{label:"Groups",children:C.map(q=>{const me=Yn({kind:"groups",groupIds:[q.id]},n,C).length;return e.jsx("option",{value:`group:${q.id}`,disabled:me===0,children:Fa(q,n)},q.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),W.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:W.groupIds.map(q=>{const me=C.find(fe=>fe.id===q);return me?e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-sm text-primary",children:[Fa(me,n),e.jsx("button",{type:"button","aria-label":`Remove ${me.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 fe=W.groupIds.filter(Z=>Z!==me.id);xe(fe.length>0?{kind:"groups",groupIds:fe}:{kind:"all"})},children:"×"})]},me.id):null})}),C.some(q=>!W.groupIds.includes(q.id)&&Yn({kind:"groups",groupIds:[q.id]},n,C).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:q=>{q.currentTarget.value&&xe({kind:"groups",groupIds:[...W.groupIds,q.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"}),C.filter(q=>!W.groupIds.includes(q.id)).map(q=>{const me=Yn({kind:"groups",groupIds:[q.id]},n,C).length;return e.jsx("option",{value:q.id,disabled:me===0,children:Fa(q,n)},q.id)})]})]}):null,le===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,W.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ir,{legend:"Specific Properties",properties:n,selectedPropertyIds:W.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:q=>{xe({kind:"specific",propertyIds:q})}})}):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."})]}),J||!j?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:re,onChange:q=>X(q.currentTarget.value),placeholder:`best apartments in dallas
|
|
6
|
+
luxury apartments atlanta
|
|
7
|
+
pet friendly apartments austin`}),f?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:f}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ve.length===0||g||i,onClick:()=>{Promise.resolve(j(Ve)).then(()=>X(""),()=>{})},children:g?"Adding…":`Add ${Ve.length||""} ${Ve.length===1?"query":"queries"}`.replace(" "," ")}),y?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:y,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:Q,onChange:q=>P(q.target.value),placeholder:"apartments near {property}"}),Q.trim()===""?null:_e.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."]}):Ue.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:[F.length," ",F.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:F.slice(0,3).map(q=>e.jsx("li",{className:"text-sm text-strong",children:q},q))}),F.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",F.length-3," more"]}):null]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Ie.length===0||g||i||!b,onClick:()=>{b&&Promise.resolve(b(Ie)).then(()=>P(""),()=>{})},children:g?"Adding…":`Add ${Ie.length||""} ${Ie.length===1?"query":"queries"}`.replace(" "," ")}),Ie.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"," ",Ie.length," assignment",Ie.length===1?"":"s","."]}):null]})]})]}),J?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:et.length===0,onClick:$,children:"Select all shown queries"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>m([]),children:"Clear query selection"}),e.jsx(A,{type:"button",size:"sm",className:"min-h-11",disabled:!je,onClick:()=>{d({queryIds:r,propertyIds:V,...W.kind==="groups"?{groupIds:W.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${Xx(W,C,le)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[c?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,R?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",R.assignmentCount," Property assignment",R.assignmentCount===1?"":"s"," · ",R.addedAssignments," new, ",R.alreadyPresentAssignments," already assigned"," · ",R.fullRunProviderCalls," provider request",R.fullRunProviderCalls===1?"":"s"," per full run"," · ",R.addedProviderCalls," new",W.kind==="groups"?` · ${R.resolvedPropertyCount} unique ${R.resolvedPropertyCount===1?"Property":"Properties"}${R.overlapCount>0?`, ${R.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):v?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}),S?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:S,children:"Retry impact"}):null,U?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:U,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",le," Properties = ",r.length*le," assignments"]})]}),D?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:D}):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:B,onChange:q=>{H(q.currentTarget.value),ke(!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 ",lt.length," queries,"," ",Ae.length-Xe.length," of ",Ae.length," applied"]}),J||Xe.length===0?null:e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{se(q=>!q),ke(!1)},children:_?"Show all queries":`Show the ${Xe.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:[J?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),J?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:we.map(q=>{const me=rr(q),fe=_a(q),Z=r.includes(q.id),Ze=(q.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[J?null:me?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 ${fe}`,checked:Z,type:"checkbox",onChange:Kt=>m(qo(r,q.id,Kt.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:fe})}),e.jsx("td",{className:"text-secondary",children:Oo(q.propertyIds??[],n)}),J?null:e.jsx("td",{className:"text-right",children:Ze?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[T?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||N,onClick:()=>Y({queryId:q.id,propertyIds:[...q.propertyIds??[]]}),"aria-label":`Replace query assignments for ${fe}`,children:"Replace assignments"}):null,e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{Fe(q.id)},"aria-label":`Clear query assignments for ${fe}`,children:"Clear assignments"})]}):null})]},q.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,J||!G?null:(()=>{const q=a.find(Z=>Z.id===G.queryId),me=q?_a(q):"this query",fe=G.propertyIds.filter(Z=>n.some(Ze=>Ze.id===Z));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 “",me,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ir,{legend:"Properties for this query",properties:n,selectedPropertyIds:fe,onSelectedPropertyIdsChange:Z=>Y(Ze=>Ze&&{...Ze,propertyIds:[...Z]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:N||i,onClick:()=>Y(null),children:"Keep current assignments"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:fe.length===0||N||i||!T,onClick:()=>{T&&Promise.resolve(T({queryId:G.queryId,propertyIds:fe}))},children:N?"Replacing assignments…":`Replace with ${fe.length} ${fe.length===1?"Property":"Properties"}`})]})]})})(),we.length<lt.length?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ke(!0),children:"Show all queries"}):null,J?null:e.jsxs(e.Fragment,{children:[u?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 ${U?"justify-between":"justify-end"}`,children:[U?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:U,children:"Back"}):null,e.jsx(A,{type:"button",variant:je?"outline":"default",className:"min-h-11",disabled:!u||i,onClick:E,children:"Continue"})]})]})]})}function sp({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:u,onEditGroup:m,onRemoveGroup:d,onClearGroupDraft:p,membershipImport:h,onBack:j,onContinue:b}){if(xr(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(gr,{message:s.message})});const g=hr(t),f=r.name.trim().length>0&&r.propertyIds.length>0&&!o,y=n.filter(R=>r.propertyIds.includes(R.id)).length,C=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,z=!g&&(m!==void 0||d!==void 0);function L(){if(p){p();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),g?e.jsx(pr,{}):null,g||!h?null:e.jsx(Zx,{value:h}),g?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:R=>i({...r,name:R.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:[y," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(ir,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:R=>i({...r,propertyIds:R})})})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Competitor domains"}),e.jsx("input",{"aria-label":"Competitor domains",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.competitorDomains,onChange:R=>i({...r,competitorDomains:R.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!f,onClick:()=>{u(r)},children:o?"Saving group…":"Save group"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!C,onClick:L,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."})]}),C?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"}),z?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(R=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:R.name}),e.jsx("td",{className:"text-secondary",children:Oo(R.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:R.competitors.length>0?R.competitors.join(", "):"None"}),z?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[m?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${R.name}`,onClick:()=>m(R),children:"Edit"}):null,d?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${R.name}`,onClick:()=>{d(R.id)},children:"Remove"}):null]})}):null]},R.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,g?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${j?"justify-between":"justify-end"}`,children:[j?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:j,children:"Back"}):null,e.jsx(A,{type:"button",className:"min-h-11",disabled:C,onClick:b,children:a.length===0&&!C?"Continue without groups":"Continue"})]})]})}function np({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:u=!1,canReviewChanges:m=!0,reviewedChanges:d,reviewChangesError:p,canPublish:h,isPublishing:j=!1,onPublish:b}){const[g,f]=l.useState(Ga),[y,C]=l.useState(Ga),[z,L]=l.useState(Ga);if(xr(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(gr,{message:s.message})});const R=hr(t),c=r?.items??[],v=r?.coverageItems??[],S=c.slice(0,g),D=v.slice(0,y),T=a.slice(0,z),N=i!==void 0,U=d!=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."})]})}),R?e.jsx(pr,{}):null,r?e.jsx("section",{"aria-labelledby":"advanced-measurement-sitemap-review-title",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{id:"advanced-measurement-sitemap-review-title",className:"text-sm font-medium text-heading",children:"Sitemap changes need review"}),r.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.exceptionCount," sitemap ",r.exceptionCount===1?"entry needs":"entries need"," review."]}):null,r.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.coverageReviewCount," ",r.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),r.exceptionCount>0?e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["URLs not added to Properties (",r.exceptionCount,")"]}),c.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:S.map(E=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:E.url}),e.jsx("p",{className:"mt-1 text-secondary",children:E.reason})]},`${E.url}-${E.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 ",c.length]}),S.length<c.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>f(E=>E+ws),children:"Show next 50 URLs"}):null]})]}):null,R?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[r.coverageReviewCount>0?e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"For changed Property URLs"}),e.jsxs("p",{className:"text-sm text-secondary",children:["This choice applies to all ",r.coverageReviewCount," changed ",r.coverageReviewCount===1?"Property":"Properties","."]}),e.jsxs("details",{className:"border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review Property URL changes (",r.coverageReviewCount,")"]}),D.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[D.map(E=>e.jsxs("section",{"aria-label":`${E.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:E.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:E.savedUrls.map(B=>e.jsx("li",{className:"break-all text-secondary",children:B},B))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),E.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:E.currentSitemapUrls.map(B=>e.jsx("li",{className:"break-all text-secondary",children:B},B))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},E.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",D.length," of ",v.length]}),D.length<v.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>C(E=>E+ws),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(A,{type:"button",className:"min-h-11",onClick:()=>{r.onResolve()},children:"Confirm sitemap changes"})]})]})}):null,e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Groups"}),e.jsx("th",{children:"Assignments"}),e.jsx("th",{children:"Provider requests / run"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-heading",children:n.properties}),e.jsx("td",{className:"tabular-nums text-heading",children:n.queries}),e.jsx("td",{className:"tabular-nums text-heading",children:n.groups}),e.jsx("td",{className:"tabular-nums text-heading",children:n.assignments??"—"}),e.jsx("td",{className:"tabular-nums text-heading",children:n.providerCalls??ep})]})})]})}),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,d?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:d.title}),d.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:d.items.map((E,B)=>e.jsx("li",{children:E},`${E}-${B}`))}):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:T.map(E=>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:E.title}),E.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:E.detail}):null]}),e.jsx(de,{tone:E.tone??"caution",children:"Needs attention"})]},E.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",T.length," of ",a.length]}),T.length<a.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>L(E=>E+ws),children:"Show next 50 exceptions"}):null]})]})]}),R?null:e.jsxs(e.Fragment,{children:[N&&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 ${o?"justify-between":"justify-end"}`,children:[o?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!U?e.jsx(A,{type:"button",className:"min-h-11",disabled:u||!m,onClick:()=>{i()},children:u?"Reviewing changes…":"Review changes"}):e.jsx(A,{type:"button",className:"min-h-11",disabled:!h||j,onClick:()=>{b()},children:j?"Publishing setup…":"Publish setup"})]})]})]})}const ap={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function rp(t){return t.trim().toLocaleLowerCase()}function ip(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function op({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 lp({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const o=!t||r==="reviewing",i=o||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function u(m,d){n({...s,[m]:d})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(de,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:m=>{m.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:o,onChange:m=>u("sitemapUrl",m.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:o,onChange:m=>u("examplePropertyUrl",m.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:o,onChange:m=>u("preferredHost",m.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:o,onChange:m=>u("propertyPathPattern",m.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:o,onChange:m=>u("additionalHost",m.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:o,onChange:m=>u("additionalPathPattern",m.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:o,onChange:m=>u("excludedPaths",m.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(A,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function cp({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:u,isContinuing:m=!1,onRetryProperties:d,onReturnToImport:p,maxVisibleProperties:h,onShowAllProperties:j}){const b=rp(a),g=s.filter(T=>ip(T,b)),f=Math.max(1,h??g.length),y=g.slice(0,f),C=new Set(o),z=s.filter(T=>C.has(T.id)).map(T=>T.id),L=y.length<g.length;function R(T){const N=new Set(T);i(s.filter(U=>N.has(U.id)).map(U=>U.id))}function c(T,N){if(!t||m)return;const U=new Set(z);N?U.add(T):U.delete(T),R(U)}function v(){!t||m||R([...z,...y.map(T=>T.id)])}function S(){!t||m||i([])}function D(){!t||m||z.length===0||u(z)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||m,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:d,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:d,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick: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:m,onChange:T=>r(T.target.value),className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:m,onClick:v,children:"Select all shown"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:m||z.length===0,onClick:S,children:"Clear selection"})]}):null]}),g.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick: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 ",y.length," of ",g.length," Properties"]}),e.jsxs("p",{children:[z.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:y.map(T=>{const N=ap[T.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:T.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(op,{property:T})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(de,{tone:N.tone,children:N.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 ${T.name}`,checked:z.includes(T.id),disabled:m,onChange:U=>c(T.id,U.target.checked),className:"size-6 accent-accent"})})}):null]},T.id)})})]})}),L&&j?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:m,onClick:j,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(A,{type:"button",variant:"ghost",disabled:m,onClick:p,children:"Back"}),e.jsx(A,{type:"button",disabled:m||z.length===0,onClick:D,children:m?"Saving Properties…":"Continue"})]}):null]}):null]})}function dp(t){return t.activeStep==="import"?e.jsx(lp,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(cp,{...t})}const up=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function mp({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),u=l.useRef(null),m=l.useRef(null),d=l.useRef(null),p=l.useRef(!1),[h,j]=l.useState(!1);return l.useEffect(()=>{s||j(!1)},[s]),l.useEffect(()=>{const b=p.current;p.current=h,h?m.current?.focus():b&&d.current?.focus()},[h]),l.useEffect(()=>{const b=i.current;if(i.current=t,b===null||b===t)return;const g=u.current?.querySelector('h1, h2, h3, [role="heading"]');g&&(g.tabIndex=-1,g.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(de,{tone:"caution",children:"Unpublished changes"}),n&&a?h?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(A,{ref:m,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>j(!1),children:"Keep editing"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(A,{ref:d,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>j(!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:up.map(b=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===b.id?"step":void 0,onClick:()=>r(b.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===b.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:b.label}):e.jsx("span",{"aria-current":t===b.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===b.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:b.label})},b.id))})}),e.jsx("div",{ref:u,children:o})]})}function hp(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(dp,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(tp,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(sp,{...t.groups,access:s}):"review"in t?e.jsx(np,{...t.review,access:s}):null}function Xn(t){return e.jsx(mp,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:hp(t)})}function Go(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Dt(t){return{"If-Match":t,"Idempotency-Key":Go()}}function Vs(t){return t instanceof en&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function es(t,s){return t instanceof en?s:(t instanceof Error?t.message.trim():"")||s}function xp(t){const s="Could not calculate assignment impact.";if(!(t instanceof en)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const pp={loadSetup:t=>ot(()=>ad({client:K,path:{name:t}})),loadDraft:t=>ot(()=>nd({client:K,path:{name:t}})),createDraft:(t,s)=>ot(()=>sd({client:K,path:{name:t},headers:{"Idempotency-Key":Go()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>ot(()=>td({client:K,path:{name:t},headers:Dt(s),body:n})),applySitemapSelection:(t,s,n,a)=>ot(()=>ed({client:K,path:{name:t},headers:Dt(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>ot(()=>Zc({client:K,path:{name:t},body:s})),applyAssignments:(t,s,n)=>ot(()=>Xc({client:K,path:{name:t},headers:Dt(s),body:n})),replaceAssignments:(t,s,n)=>ot(()=>Jc({client:K,path:{name:t},headers:Dt(s),body:n})),applyPairedAssignments:(t,s,n)=>ot(()=>Yc({client:K,path:{name:t},headers:Dt(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>ot(()=>Wc({client:K,path:{name:t},headers:Dt(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>ot(()=>Hc({client:K,path:{name:t},headers:Dt(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>ot(()=>Qc({client:K,path:{name:t},headers:Dt(s),body:{target:n}})),upsertGroup:(t,s,n)=>ot(()=>zc({client:K,path:{name:t},headers:Dt(s),body:{group:n}})),removeGroup:(t,s,n)=>ot(()=>Kc({client:K,path:{name:t},headers:Dt(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>ot(()=>Vc({client:K,path:{name:t},headers:Dt(s),body:n})),removeCompetitor:(t,s,n,a)=>ot(()=>Bc({client:K,path:{name:t},headers:Dt(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>ot(()=>Uc({client:K,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>ot(()=>_c({client:K,path:{name:t},headers:Dt(s),body:n})),compilePreview:t=>ot(()=>Fc({client:K,path:{name:t}})),diffPreview:t=>ot(()=>Gc({client:K,path:{name:t}})),publish:(t,s,n)=>ot(()=>Oc({client:K,path:{name:t},headers:Dt(s),body:n})),discard:(t,s)=>ot(()=>qc({client:K,path:{name:t},headers:Dt(s)}))},Ci={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},Sn={name:"",propertyIds:[],competitorDomains:""},ki=50;function An(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function gp(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 Ai(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(i=>i==="*"||i==="{slug}").length!==1||r.some(i=>i.includes("*")&&i!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(i=>i==="*"?"{slug}":i).join("/")}`}const n=t.examplePropertyUrl.trim();if(!n)throw new Error("Add one example Property page so Canonry can identify the matching URLs.");try{const a=new URL(n).pathname.split("/").filter(Boolean);if(a.length===0)throw new Error;return a[a.length-1]="{slug}",`/${a.join("/")}`}catch{throw new Error("Example Property page must be a valid web address.")}}function fp(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,u=i.startsWith("*"),m=i.endsWith("*"),d=i.slice(u?1:0,m?-1:void 0).trim();if(!d)throw new Error("Ignored URL patterns must include text besides *.");const p=u&&m?"contains":u?"suffix":m?"prefix":"exact",h=`${p}:${d}`;n.has(h)||(n.add(h),s.push({kind:p,value:d}))}return s}function bp(t){const s=gp(t.sitemapUrl),n=t.examplePropertyUrl.trim()?An(t.examplePropertyUrl):null,a=An(t.preferredHost)??n??An(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=An(t.additionalHost),o=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(o!==i||o&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const u=fp(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Ai(t)},...r?{aliases:[{host:r,pathTemplate:Ai({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...u.length>0?{excludedSlugPatterns:u}:{}}}}function yp(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 vp(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 Pi(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function jp(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Ua(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function or(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function Ri(t){return An(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 _o(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 Uo(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Bo(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Np(t,s){const n=Fo(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const o=n.urlMatchers[r];return o?`${n.label} — ${o}`:n.label}if(a==="aliases"&&typeof r=="number"){const o=n.aliases[r];return o?`${n.label} — ${o}`:n.label}return n.label}function wp(t,s){const n=_o(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const o=n.competitors.at(r)?.domain;return o?`${n.label} — ${o}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const o=Bo(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function Sp(t,s){const n=Uo(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Bo(t.authoring,n.targetKey)} — ${a}`}function Cp(t,s){return s.path[0]==="identities"?"Project domain":Np(t,s)??wp(t,s)??Sp(t,s)}function Ii(t,s,n){const a=Uo(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},o=s.path.at(-1);if(n==="models"&&typeof o=="string")return r.models?.[o];if(n==="locations"&&typeof o=="number")return r.locations?.[o]}function kp(t,s){const n=Cp(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,Ii(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,Ii(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 Zn(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Vo(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 Ap(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Zn(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Zn(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Zn(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Zn(n,"item")} need review.`:s}})()}${Vo(a)}`}function Pp(t,s){const n=new Map;for(const a of t){const r=kp(a,s),o=[a.ruleId,a.severity,r.title,r.detail].join("\0"),i=n.get(o)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};i.paths.add(JSON.stringify(a.path)),r.affected&&i.affected.add(r.affected),n.set(o,i)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:Ap(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Ba(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Va(t,s,n){const a=Fo(n,t.path),r=_o(n,t.path),o=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=o?n?.targets.find(p=>p.stableKey===o):void 0,u=a?.label??r?.label,m=Vo(u?[u]:[]),d={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...d,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${m}`};case"excluded-target-has-assignments":return{...d,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${m}`};case"group-unknown-target":return{...d,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${m}`};case"measurement.discovery.proposed_new_target":{const p=Ba(a)??"the proposed Property";return{...d,title:"Review a new Property",detail:`Review ${p}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const p=Ba(a)??"the proposed Property",h=i?.label??"an existing Property";return{...d,title:"Review a moved Property",detail:`Review ${p}. It may be the same Property as ${h}.`}}case"measurement.discovery.rebind_ambiguous":{const p=Ba(a)??"the proposed Property",h=i?.label??"an existing Property";return{...d,title:"Choose an existing Property",detail:`Review ${p}. It may match ${h}; choose the correct Property.`}}default:return{...d,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function Rp(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,r=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,o=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),o>0&&n.push(`${o} query assignment ${o===1?"change":"changes"}`),r>0&&n.push(`${r} group ${r===1?"change":"changes"}`),s&&n.unshift("Existing results remain visible after you publish this setup."),{title:s?"Historical results will be kept":t.activeRevision===null?"New setup ready":"Changes ready",items:n.length>0?n:["No changes from the published setup."]}}function gs(t){return[...new Set(t)]}function Es(t){return gs(t).sort()}function Ip(t,s,n){return t.kind==="groups"?{groupKeys:Es(t.groupIds),queryIds:Es(n)}:{targetKeys:Es(t.kind==="all"?s:t.propertyIds),queryIds:Es(n)}}function $p(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 $i(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Tp(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($i).filter(Boolean),source:a.discoveryIdentity?"sitemap":"manual",...a.discoveryIdentity?{discoveryIdentity:a.discoveryIdentity}:{}})),assignments:s.assignments.map(a=>({targetKey:a.targetKey,queryId:a.queryId,queryClass:a.queryClass,classificationSource:"operator"})),groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:a.competitors.map(r=>({...r,aliases:[...r.aliases]}))}))};const n=s.targetQuerySelections.flatMap(a=>a.queryIds.map(r=>({targetKey:a.targetKey,queryId:r,queryClass:"unclassified",classificationSource:"rule"})));return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urls.map($i).filter(Boolean),source:"manual"})),assignments:n,groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:(a.competitors??[]).map(r=>({stableKey:or(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function Mp({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:u,onManageProjectQueries:m,onPublished:d,service:p=pp}){const[h,j]=l.useState(null),[b,g]=l.useState(null),[f,y]=l.useState("import"),[C,z]=l.useState(!0),[L,R]=l.useState(null),[c,v]=l.useState(null),[S,D]=l.useState([]),[T,N]=l.useState({...Ci}),[U,E]=l.useState("idle"),[B,H]=l.useState(""),[ge,ke]=l.useState(ki),[_,se]=l.useState([]),[re,X]=l.useState([]),[Q,P]=l.useState({kind:"all"}),[G,Y]=l.useState(null),[J,W]=l.useState(null),[xe,V]=l.useState(!1),[le,je]=l.useState(null),[Fe,Le]=l.useState(0),[Ae,Xe]=l.useState(null),[lt,we]=l.useState({...Sn}),[et,Ve]=l.useState(null),[_e,Ue]=l.useState(""),[Ie,F]=l.useState(null),[$,q]=l.useState(!1),[me,fe]=l.useState(!1),[Z,Ze]=l.useState(null),[Kt,Ye]=l.useState(null),[$e,Te]=l.useState(null),[pt,ct]=l.useState(null),[Oe,Qe]=l.useState(null),vt=l.useRef(0),Ke=l.useRef(0),Ee=b?.draft??null,qe=b?.etag??null,jt=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:Tp(o)}:null,[i,o]),Ge=Ee??jt;async function It(I){const ee=++vt.current;z(!0),R(null);try{let[pe,ne]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);if(!ne.draft&&I&&i&&(await p.createDraft(t,pe.activeRevision),[pe,ne]=await Promise.all([p.loadSetup(t),p.loadDraft(t)])),ee!==vt.current)return;j(pe),g(ne),y(yp(ne.draft));const ie=Ua(ne.draft);se(ie)}catch(pe){if(ee!==vt.current)return;R(es(pe,"Could not load advanced measurement setup."))}finally{ee===vt.current&&z(!1)}}l.useEffect(()=>(It(!0),()=>{vt.current+=1}),[t,i,p]),l.useEffect(()=>{!C&&!Ee&&jt&&y("properties")},[Ee,C,jt]);async function Gt(){const I=await p.loadDraft(t);return g(I),I}async function gt(I){Qe(null);try{const[ee,pe]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);j(ee),g(pe);const ne=Ua(pe.draft);se(ne),y(ie=>vp(pe.draft,ie)),v(I)}catch(ee){v(es(ee,I))}}async function kt(I,ee,pe,ne={}){const{preserveBusyAction:ie=!1}=ne;if(!i||!qe||$e&&!ie)return null;ie||Te(I),v(null),Qe(null);try{const Me=await ee(qe),$t=await Gt();return D((Me.warnings??[]).map((ut,As)=>Va(ut,As,$t.draft?.authoring))),$t}catch(Me){return Vs(Me)?await gt("This setup changed in another session. The latest draft is loaded; review your changes again."):v(es(Me,pe)),null}finally{ie||Te(null)}}const ht=l.useMemo(()=>(Ge?.authoring.targets??[]).map(I=>{const ee=Pi(I);return{id:I.stableKey,name:I.label,url:ee[0]??"No URL",urls:ee,state:jp(I.status)}}),[Ge]),O=l.useMemo(()=>Ge?.authoring.targets.filter(I=>I.status==="included")??[],[Ge]),Se=l.useMemo(()=>O.map(I=>({id:I.stableKey,label:I.label,urlCount:Pi(I).length})),[O]),be=Ge?.authoring.assignments.length??0,ve=l.useMemo(()=>{if(!Ge)return[];const I=new Set(s.map(ne=>ne.id)),ee=s.map(ne=>({id:ne.id,text:ne.query,source:"saved-project-queries",propertyIds:gs(Ge.authoring.assignments.filter(ie=>ie.queryId===ne.id).map(ie=>ie.targetKey))})),pe=gs(Ge.authoring.assignments.map(ne=>ne.queryId).filter(ne=>!I.has(ne))).map(ne=>({id:ne,source:"unavailable-tracked-query",state:"missing",propertyIds:gs(Ge.authoring.assignments.filter(ie=>ie.queryId===ne).map(ie=>ie.targetKey))}));return[...ee,...pe]},[s,Ge]),ft=l.useMemo(()=>(Ge?.authoring.groups??[]).map(I=>({id:I.stableKey,name:I.label,propertyIds:I.targetKeys,competitors:I.competitors.map(ee=>ee.domain)})),[Ge]),Je=l.useMemo(()=>{if(re.length===0)return null;const I=Ip(Q,Se.map(pe=>pe.id),re);return(I.groupKeys?.length??I.targetKeys?.length??0)>0?I:null},[Q,Se,re]),At=Je?JSON.stringify(Je):"";l.useEffect(()=>{const I=Je,ee=++Ke.current;if(!i||!Ee||!qe||!I){Y(null),W(null),je(null),V(!1);return}Y(null),W(null),je(null),V(!0);const pe=window.setTimeout(()=>{p.previewAssignments(t,I).then(ne=>{if(ee===Ke.current){if(ne.draftEtag!==qe){Y(null),W(null),je("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}Y(ne),W(At)}}).catch(ne=>{ee===Ke.current&&(Y(null),W(null),je(xp(ne)))}).finally(()=>{ee===Ke.current&&V(!1)})},250);return()=>{window.clearTimeout(pe),Ke.current+=1}},[Je,At,Fe,i,Ee,qe,t,p]);const Nt=l.useMemo(()=>[...be===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...Ge?.authoring.assignments.some(I=>I.queryClass==="unclassified")&&!(jt&&o?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...S],[be,jt,o,S,Ge]),rs=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 is(I){let ee;try{ee=bp(I)}catch(ne){v(es(ne,"Check the sitemap details and try again."));return}N(I),E("reviewing");const pe=await kt("import",ne=>p.importSitemap(t,ne,ee),"Could not review this sitemap.");if(pe?.draft){const ne=pe.draft.authoring.targets.filter(Me=>Me.status==="proposed").map(Me=>Me.stableKey),ie=pe.draft.authoring.targets.filter(Me=>Me.status==="included").map(Me=>Me.stableKey);se([...ie,...ne]),H(""),ke(ki),y("properties"),E("idle")}else E("error")}async function cs(I){if(!u||I.length===0||$e)return[];Te("create-queries"),ct(null);try{return await u(I)}catch(ee){throw ct(mt(ee)),ee}finally{Te(null)}}async function rt(I){if(!Ee||!qe||$e)return;const ee=new Set(I),ne=Ee.authoring.targets.filter(Me=>Me.status==="proposed"&&Me.discoveryIdentity).map(Me=>({discoveryIdentity:Me.discoveryIdentity,action:ee.has(Me.stableKey)?"create":"ignore"})),ie=ne.length>0||Ee.authoring.targets.some(Me=>Me.status!=="proposed"&&Me.status==="included"!==ee.has(Me.stableKey));Te("properties"),v(null),Qe(null);try{if(!ie){se([...ee]),P({kind:"all"}),y("groups");return}await p.applySitemapSelection(t,qe,ne,[...ee]);const Me=await Gt(),$t=Ua(Me.draft);se($t),P({kind:"all"}),y("groups")}catch(Me){Vs(Me)?await gt("This setup changed in another session. The latest Properties are loaded."):v(es(Me,"Could not save the selected Properties."))}finally{Te(null)}}async function ds(I){const ee=I.groupIds&&I.groupIds.length>0?{groupKeys:Es(I.groupIds),queryIds:Es(I.queryIds)}:{targetKeys:Es(I.propertyIds),queryIds:Es(I.queryIds)};if(!G||J!==JSON.stringify(ee)||!qe||G.draftEtag!==qe){v("Review the latest assignment impact before assigning queries.");return}await kt("assignments",ne=>p.applyAssignments(t,ne,ee),"Could not apply these queries.")&&(X([]),Xe(`${G.assignments.added} new assignment${G.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function dt(I){if(I.propertyIds.length===0)return;await kt("replace-assignments",pe=>p.replaceAssignments(t,pe,{targetKeys:gs(I.propertyIds),queryIds:[I.queryId]}),"Could not replace this query assignment.")&&(X(pe=>pe.filter(ne=>ne!==I.queryId)),Xe("Query assignments replaced."))}async function bs(I,ee=!1){if(I.length===0)return;if(!await kt("paired-assignments",ne=>p.applyPairedAssignments(t,ne,[...I]),"Could not assign these queries.",{preserveBusyAction:ee}))throw new Error("Could not assign these queries.")}async function Wt(I){if(!(!i||!u||I.length===0||$e)){Te("create-and-pair-questions"),ct(null);try{let ee;try{ee=await u(gs(I.map(ie=>ie.text)))}catch(ie){throw ct(mt(ie)),ie}const pe=new Map(ee.map(ie=>[ie.query,ie.id])),ne=I.map(ie=>({targetKey:ie.propertyId,queryId:pe.get(ie.text)})).filter(ie=>ie.queryId!==void 0);if(ne.length!==I.length){const ie=new Error("The created queries could not be matched to their Properties.");throw ct("The queries were added, but could not be paired with every Property. Try again to pair them."),ie}try{await bs(ne,!0)}catch(ie){throw ct("The queries were added, but could not be assigned to their Properties. Try again to pair them."),ie}}finally{Te(null)}}}async function zt(I){if(!Ee)return;const ee=gs(Ee.authoring.assignments.filter(ne=>ne.queryId===I).map(ne=>ne.targetKey));if(ee.length===0)return;await kt(`remove-${I}`,ne=>p.removeAssignment(t,ne,ee,I),"Could not clear this query assignment.")&&X(ne=>ne.filter(ie=>ie!==I))}async function Yt(I){if(!Ee||!qe||$e)return;const ee=I.name.trim();if(!ee)return;const pe=et??or(ee,"group"),ne=Ee.authoring.groups.find(ut=>ut.stableKey===pe);if(ne&&et===null){v(`A group named "${ne.label}" already exists. Edit it or choose a different name.`);return}const ie=I.competitorDomains.split(/[\s,]+/).map(ut=>ut.trim()).filter(Boolean),Me=ie.find(ut=>Ri(ut)===null);if(Me){v(`"${Me}" is not a valid competitor domain.`);return}const $t=gs(ie.map(ut=>Ri(ut)));Te("group"),v(null),Qe(null);try{const ut=await p.upsertGroup(t,qe,{stableKey:pe,label:ee,targetKeys:gs(I.propertyIds),competitors:$t.map(w=>ne?.competitors.find(oe=>oe.domain===w)??{stableKey:or(w,"competitor"),label:w,domain:w,aliases:[]})}),As=await Gt();D(ut.warnings.map((w,oe)=>Va(w,oe,As.draft?.authoring))),we({...Sn}),Ve(null)}catch(ut){Vs(ut)?await gt("This setup changed in another session. The latest groups are loaded."):v(es(ut,"Could not save this group."))}finally{Te(null)}}function wt(I){const ee=Ee?.authoring.groups.find(pe=>pe.stableKey===I);ee&&(Ve(I),we({name:ee.label,propertyIds:[...ee.targetKeys],competitorDomains:ee.competitors.map(pe=>pe.domain).join(", ")}))}async function us(I){await kt("remove-group",pe=>p.removeGroup(t,pe,I),"Could not remove this group.")&&(P(pe=>pe.kind==="groups"&&pe.groupIds.includes(I)?{kind:"all"}:pe),et===I&&(Ve(null),we({...Sn})))}function Qt(I){Ue(I),F(null),Ze(null),Ye(null)}async function bt(){if(!(!i||!_e.trim()||$||me)){q(!0),Ze(null),Ye(null);try{F(await p.previewGroupMembership(t,{csv:_e}))}catch(I){F(null),Ze(es(I,"Could not review this CSV."))}finally{q(!1)}}}async function ys(I){if(!(!i||!qe||!Ie||I.length===0||$e)){if(Ie.draftEtag!==qe){Ze("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}fe(!0),Te("group-import"),Ze(null),Ye(null),Qe(null);try{const ee=await p.applyGroupMembership(t,qe,{csv:_e,sourceChecksum:Ie.sourceChecksum,previewChecksum:Ie.previewChecksum,acceptedRows:gs(I.map(String)).map(Number)}),pe=await Gt();D(ee.warnings.map((ne,ie)=>Va(ne,ie,pe.draft?.authoring))),Ue(""),F(null),Ye(`${ee.addedMemberships} membership${ee.addedMemberships===1?"":"s"} added${ee.unchangedMemberships>0?`; ${ee.unchangedMemberships} already present`:""}.`)}catch(ee){Vs(ee)?(await gt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ze("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ze(es(ee,"Could not apply this CSV."))}finally{Te(null),fe(!1)}}}async function Pt(){if(!(!Ee||!qe||$e||be===0)){Te("review"),v(null),Qe(null);try{const[I,ee]=await Promise.all([p.compilePreview(t),p.diffPreview(t)]),pe=[...I.checks,...ee.checks],ne=pe.some(ie=>ie.ruleId==="active-revision-schema-v1");if(D(Pp(pe.filter(ie=>ie.ruleId!=="active-revision-schema-v1"),{authoring:Ge?.authoring,queries:s})),!I.ok||!ee.ok)return;if(ee.diff.activeRevision!==Ee.baseActiveRevision){await gt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(I.compiledChecksum!==ee.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}Qe({etag:qe,baseActiveRevision:Ee.baseActiveRevision,compiledChecksum:I.compiledChecksum,changes:Rp(ee.diff,ne),providerCalls:I.plan.executionNodes.reduce((ie,Me)=>ie+Me.expectedSnapshots,0)})}catch(I){v(es(I,"Could not review this setup."))}finally{Te(null)}}}async function ms(){if(!(!Ee||!qe||!Oe||$e)){if(qe!==Oe.etag||Ee.baseActiveRevision!==Oe.baseActiveRevision){Qe(null),v("The setup changed after review. Review the latest changes before publishing.");return}Te("publish"),v(null);try{await p.publish(t,qe,{expectedActiveRevision:Oe.baseActiveRevision,expectedCompiledChecksum:Oe.compiledChecksum}),g({draft:null,etag:null}),Qe(null),d?.()}catch(I){Vs(I)?await gt("The setup changed before it could be published. Review the latest draft and publish again."):v(es(I,"Could not publish this setup."))}finally{Te(null)}}}async function hs(){if(!(!qe||$e)){Te("discard"),v(null);try{await p.discard(t,qe),g({draft:null,etag:null}),Qe(null),d?.()}catch(I){Vs(I)?await gt("This setup changed in another session. The latest draft is loaded."):v(es(I,"Could not discard these changes."))}finally{Te(null)}}}async function xs(){if(!(!Ee||!qe||!h||$e)){Te("restart"),v(null),Qe(null);try{await p.discard(t,qe),await p.createDraft(t,h.activeRevision),N({...Ci}),H(""),se([]),X([]),P({kind:"all"}),Y(null),je(null),Xe(null),we({...Sn}),Ve(null),Ue(""),F(null),Ze(null),Ye(null),await It(!1)}catch(I){Vs(I)?await gt("The setup changed again. Reloaded the latest draft and published setup."):v(es(I,"Could not restart this setup."))}finally{Te(null)}}}if(C)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(L)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:L}),e.jsx(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{It(!0)},children:"Try again"})]})]});if(!Ge||i&&!qe)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-empty-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-empty-title",children:"Advanced measurement setup"})}),e.jsx("p",{className:"text-sm text-secondary",children:i?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(i&&Ee&&h&&Ee.baseActiveRevision!==h.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:$e==="restart",onClick:()=>{xs()},children:$e==="restart"?"Restarting…":"Discard draft and restart"})]}),c?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:c}):null]});const St=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[h?.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,c?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:c}):null,St,f==="import"||f==="properties"?e.jsx(Xn,{currentStep:f,hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{hs()},importProperties:{importDraft:T,onImportDraftChange:I=>{N(I),E("idle"),v(null)},onReviewSitemap:I=>{is(I)},reviewState:U,properties:ht,propertiesState:"ready",propertiesSearch:B,onPropertiesSearchChange:H,maxVisibleProperties:ge,onShowAllProperties:()=>ke(ht.length),selectedPropertyIds:_,onSelectedPropertyIdsChange:I=>se([...I]),onContinue:I=>{rt(I)},isContinuing:$e==="properties",onRetryProperties:()=>{Gt()},onReturnToImport:()=>y("import")}}):f==="queries"?e.jsx(Xn,{currentStep:"queries",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{hs()},onManageProjectQueries:m,queries:{onCreateQueries:u?I=>cs(I):void 0,isCreatingQueries:$e==="create-queries"||$e==="create-and-pair-questions",isBusy:$e!==null,createQueriesError:pt,availability:rs,properties:Se,queries:ve,selectedQueryIds:re,isApplying:$e==="assignments"||$e==="paired-assignments",onSelectedQueryIdsChange:I=>X([...I]),onApplySelectedQueries:I=>ds(I),groups:ft,audience:Q,onAudienceChange:I=>{P(I),Xe(null)},assignmentImpact:G&&J===At?$p(G):null,isPreviewingAssignmentImpact:xe,assignmentImpactError:le,onRetryAssignmentImpact:()=>Le(I=>I+1),assignmentNotice:Ae,onReplaceAssignments:dt,isReplacingAssignments:$e==="replace-assignments",onCreateAndPairQuestions:i&&u?Wt:void 0,onClearQueryAssignments:zt,onRemoveQuery:zt,canContinue:be>0,onBack:()=>y("groups"),onContinue:()=>y("review")}}):f==="groups"?e.jsx(Xn,{currentStep:"groups",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{hs()},groups:{properties:Se,groups:ft,groupDraft:lt,isSaving:$e==="group",onGroupDraftChange:we,onSaveGroup:Yt,onEditGroup:I=>wt(I.id),onRemoveGroup:us,onClearGroupDraft:()=>{Ve(null),we({...Sn})},membershipImport:{csv:_e,preview:Ie,isReviewing:$,isApplying:me,error:Z,notice:Kt,onCsvChange:Qt,onReview:bt,onApply:ys},onBack:()=>{y("properties")},onContinue:()=>y("queries")}}):e.jsx(Xn,{currentStep:"review",hasDraft:Ee!==null,canEdit:i,onStepChange:i?void 0:y,onDiscard:()=>{hs()},review:{counts:{properties:O.length,queries:new Set(Ge.authoring.assignments.map(I=>I.queryId)).size,groups:Ge.authoring.groups.length,assignments:Ge.authoring.assignments.length,providerCalls:Oe?.providerCalls},flaggedExceptions:Nt,reviewedChanges:Oe?.changes,isReviewing:$e==="review",canReviewChanges:be>0&&!$e,onReviewChanges:Pt,onBack:()=>y("queries"),canPublish:Oe!==null&&!$e,isPublishing:$e==="publish",onPublish:ms}})]})}const Lp=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Ti(t){return t.label!=="Complete"}const Ks="__all_properties__",Dp=50,Ko=50,Ep=20,qp=50,Op=250,Gp=5,Fp=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],_p={"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"},zo={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."},Up={numerator:null,denominator:null,reason:"plan_v1"};function In(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 Bp(t){return In(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function Qo(t){if(In(t))return"";const s=t.reason??"unavailable";return zo[s]??s}function Mi(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 Vp(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function Kp(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function zp(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function Pn({metric:t,compact:s=!1}){const n=s?In(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":In(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",...In(t)?{}:{title:Qo(t)},children:e.jsx("span",{className:n,children:Bp(t)})})}function fr({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(A,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Li({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(Ko),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((u,m)=>e.jsx("li",{className:a,children:u},`${u}:${m}`))}),e.jsx(fr,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function Qp({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(Ko),o=t.slice(0,a);return e.jsxs("section",{"aria-label":"Evidence",children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:"Evidence"}),s==="loading"?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Loading evidence…"}):s==="error"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsx("span",{children:"Evidence could not be loaded."}),n?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:o.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(de,{tone:i.tone,children:_p[i.kind]}),i.historical?e.jsx(de,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(fr,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Hp({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Li,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Li,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(Qp,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Wp({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(Pn,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Di({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const u=n.findIndex(p=>p.value===s);let m=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?m=(u+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?m=(u-1+n.length)%n.length:i.key==="Home"?m=0:i.key==="End"&&(m=n.length-1),m===null)return;i.preventDefault();const d=n[m];a(d.value),i.currentTarget.querySelectorAll('[role="radio"]')[m].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const u=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":u,tabIndex:u?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${u?"segmented-option-active":""}`,children:i.label},i.value)})})}function Yp({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(ze,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function Jp({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:u=!1,isLoadMoreError:m=!1,viewSearch:d,onViewChange:p,onLoadMore:h,onPropertyExpand:j,onRetryEvidence:b,renderPropertyLink:g}){const f=t.currentView!=null,y=t.classReporting==="available"&&(f||t.classScopes!=null),[C,z]=l.useState(t.currentView?.queryClass??"all"),[L,R]=l.useState(t.currentView?.scope.key??Ks),[c,v]=l.useState(d??""),[S,D]=l.useState(Dp),[T,N]=l.useState(Ep),[U,E]=l.useState(t.currentView?.sort??"label-asc"),[B,H]=l.useState(null),ge=l.useRef(d??""),ke=y&&!f&&C!=="all"?C==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,_=f?{aggregate:t.currentView.aggregate,groups:[]}:ke,se=l.useCallback(F=>{if(!f||!p)return;const $=F.scope??(L===Ks?"all":"group"),q=F.search??c;ge.current=q,p({scope:$,...$==="group"?{groupKey:F.groupKey??L}:{},queryClass:F.queryClass??C,...q?{search:q}:{},...F.sort?{sort:F.sort}:{}})},[p,c,C,L,f]);l.useEffect(()=>{!t.currentView||i||(z(t.currentView.queryClass),R(t.currentView.scope.key??Ks),t.currentView.sort&&E(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{d!==void 0&&(ge.current=d,v(F=>F.trim()===d.trim()?F:d))},[d]),l.useEffect(()=>{if(!f||!p||c===ge.current)return;const F=window.setTimeout(()=>se({search:c}),Op);return()=>window.clearTimeout(F)},[p,se,c,f]);const re=t.availableGroups??_.groups;l.useEffect(()=>{L===Ks||re.some(F=>F.id===L)||R(Ks)},[re,L]);const X=f?void 0:_.groups.find(F=>F.id===L),Q=X?.aggregate??_.aggregate,P=F=>y?F:Up,G=U,Y=c.trim().toLocaleLowerCase(),J=l.useMemo(()=>!f&&Y?Q.properties.filter(F=>F.name.toLocaleLowerCase().includes(Y)):Q.properties,[Q.properties,Y,f]),W=f?J:J.slice(0,S),xe=(f?t.currentView?.scope.kind==="group":X!=null)&&C==="non-brand"&&y&&(f||X.confirmedCompetitorCount>0)&&(Q.shareOfVoice?.length??0)>0,V=y?Q.unavailablePropertyCount??0:0,le=t.flaggedResults.reduce((F,$)=>F+($.count??1),0),je=t.flaggedResultsTotal??le,Fe=[P(Q.metrics.propertiesMentioned),P(Q.metrics.mentionCoverage),P(Q.metrics.citationCoverage)].map(Qo).find(Boolean),Le=y?t.nextActionText??Fe??(V>0?`${V} ${V===1?"property is":"properties are"} unavailable.`:je>0?`${je} flagged ${je===1?"result needs":"results need"} review.`:null):zo.plan_v1,lt=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?Vp(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,we=Kp(t.latestMeasurement.date),et=[{value:Ks,label:"All properties"},...re.map(F=>({value:F.id,label:F.label}))],Ve=re.length>Gp;function _e(F){R(F),se(F===Ks?{scope:"all"}:{scope:"group",groupKey:F})}function Ue(F){z(F),se({queryClass:F})}function Ie(F){const $=B!==F;H($?F:null),$&&j?.(F)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(de,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(de,{tone:"caution",children:"Includes historical data"}):null,lt?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:lt}):null,we?e.jsx("span",{className:"text-sm text-secondary",children:we}):null,Le?e.jsx("span",{className:"text-sm text-secondary",children:Le}):null,s&&y&&n?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!y?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||o,children:o?"Opening setup…":"Republish setup"}):null]})})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-b border-default pb-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-group-label",htmlFor:Ve?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Ve?e.jsx("select",{id:"advanced-measurement-group",value:L,onChange:F=>_e(F.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:et.map(F=>e.jsx("option",{value:F.value,children:F.label},F.value))}):e.jsx(Di,{ariaLabelledBy:"advanced-measurement-group-label",value:L,options:et,onChange:_e})]}),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(Di,{ariaLabelledBy:"advanced-measurement-class-label",value:C,options:Fp,onChange:Ue,disabled:!y})]}),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:c,onChange:F=>v(F.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&xe?e.jsx(Wp,{values:Q.shareOfVoice??[]}):null,i?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(ze,{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??J.length," ",(t.currentView?.propertyTotal??J.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Yp,{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:[Lp.map(F=>{const $=G.startsWith(`${F.key}-`),q=$&&G.endsWith("-desc")?"descending":$?"ascending":"none";return e.jsx("th",{"aria-sort":q,className:(F.numeric,void 0),children:p?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const me=`${F.key}-${$&&G.endsWith("-asc")?"desc":"asc"}`;E(me),se({sort:me})},"aria-label":`Sort by ${F.label.toLowerCase()}`,children:[F.label,e.jsx(oa,{className:`h-3 w-3 transition-transform ${$?"opacity-100":"opacity-0"} ${q==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):F.label},F.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[W.map(F=>{const $=B===F.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:q=>{zp(q.target)||Ie(F.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[g?g({id:F.id,name:F.name}):F.name,Ti(F.status)||F.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Ti(F.status)?e.jsx(de,{tone:F.status.tone,children:F.status.label}):null,F.historical?e.jsx(de,{tone:"caution",children:"Historical"}):null]}):null,Mi(F)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Mi(F)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(Pn,{metric:F.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Pn,{metric:F.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{size:"icon",variant:"ghost","aria-expanded":$,"aria-label":$?`Hide details for ${F.name}`:`Show details for ${F.name}`,onClick:()=>Ie(F.id),children:e.jsx(oa,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${$?"rotate-180":""}`,"aria-hidden":"true"})})})]},F.id),$?(F.providers??[]).map(q=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:q.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(Pn,{metric:q.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Pn,{metric:q.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${F.id}:${q.provider}`)):null,$?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Hp,{property:F,onRetryEvidence:b})})},`${F.id}:details`):null]},F.id)}),W.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]})]})}),f&&t.currentView.nextCursor&&h?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",W.length," of ",t.currentView.propertyTotal]}),m?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(A,{size:"sm",variant:"outline",disabled:u,onClick:()=>h(t.currentView.nextCursor),children:u?"Loading…":m?"Retry loading more properties":"Show 50 more"})]}):f?W.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",W.length," of ",t.currentView.propertyTotal]}):null:e.jsx(fr,{shown:W.length,total:J.length,itemLabel:"properties",onShowAll:()=>D(Number.MAX_SAFE_INTEGER)})]}),!i&&!Y&&je>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 (",je,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,T).map(F=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(de,{tone:F.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:F.property}),e.jsx("span",{className:"text-secondary",children:F.summary})]},F.id))}),T<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,T).reduce((F,$)=>F+($.count??1),0)," of ",je," flagged results"]}),e.jsx(A,{size:"sm",variant:"outline",onClick:()=>N(F=>Math.min(t.flaggedResults.length,F+qp)),children:"Show 50 more"})]}):le<je?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",le," of ",je," flagged results"]}),f&&t.currentView.nextCursor&&h?e.jsx(A,{size:"sm",variant:"outline",disabled:u,onClick:()=>h(t.currentView.nextCursor),children:u?"Loading…":m?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function Ho(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function Xp(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 Zp({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:u,onViewChange:m,onLoadMore:d,onPropertyExpand:p,onRetryEvidence:h,renderPropertyLink:j,isRunningMeasurement:b,isOpeningSetup:g,isViewLoading:f,isLoadingMore:y,isLoadMoreError:C,viewSearch:z}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&o?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",disabled:g,onClick:o,children:g?"Opening setup…":Ho(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),u?e.jsx(A,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:u,children:"Retry report"}):null]}):a?e.jsx(Jp,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:m,onLoadMore:d,onPropertyExpand:p,onRetryEvidence:h,renderPropertyLink:j,isRunningMeasurement:b,isRepublishingSetup:g,isViewLoading:f,isLoadingMore:y,isLoadMoreError:C,viewSearch:z}):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 hn={numerator:null,denominator:null,reason:"plan_v1"};function eg(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Ei(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function tg(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function sg(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function ng(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 ag(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function rg(t){const s=new Map;for(const n of t){const a=ag(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function ig(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(g=>[g.stableKey,g])),r=new Map(n.querySnapshots.map(g=>[g.queryId,g.queryText])),o=new Map;for(const g of n.targetQuerySelections){const f=o.get(g.targetKey)??[];f.push(...g.queryIds.map(y=>r.get(y)).filter(y=>!!y)),o.set(g.targetKey,[...new Set(f)])}const i=rg(s.evidence),u=n.executionNodes.reduce((g,f)=>g+f.expectedSnapshots,0),m=s.run?.status==="completed"&&u>0,d=m?u:0,p=m?u:0,h=s.targets.map(g=>{const f=a.get(g.id),y=i.get(g.id)??[],C=y.map(R=>({id:`${R.observationId}:${R.usageEdgeId}:${R.sourceUrl}`,kind:tg(R.classification),query:R.queryText,url:R.sourceUrl,tone:sg(R.classification),historical:R.historical||R.bridged})),z=y.some(R=>R.historical||R.bridged),L=s.run?g.completeness.complete?f?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${g.completeness.executed} of ${g.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:g.id,name:g.label,mentionCoverage:Ei(g.mentionCoverage),citationCoverage:Ei(g.citationCoverage),status:L,assignedQueries:o.get(g.id)??[],urls:f?.urls.map(eg)??[],evidence:C,historical:z}}),j=new Map(h.map(g=>[g.id,g])),b=new Map(n.groups.map(g=>[g.stableKey,g]));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:d,totalSlots:p,date:ng(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:hn,mentionCoverage:hn,citationCoverage:hn},properties:h},groups:s.groups.map(g=>({id:g.id,label:g.label,confirmedCompetitorCount:b.get(g.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:hn,mentionCoverage:hn,citationCoverage:hn},properties:g.targetIds.map(f=>j.get(f)).filter(f=>!!f)}}))},flaggedResults:[]}}const og={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function xt(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 lg(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 cg(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function dg({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(rd),u=Re({...id({client:K,path:{name:t},query:{period:o}}),placeholderData:Ki});async function m(){n(!0),r(null);try{await ld(t,"client",o)}catch(p){const h=p instanceof en||p instanceof Error?p.message:"Download failed";r(h)}finally{n(!1)}}if(u.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(u.error){const p=u.error instanceof Error?u.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 d=u.data;return d?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:d.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[d.meta.project.canonicalDomain," · ",d.meta.project.country," / ",d.meta.project.language.toUpperCase(),d.meta.location?` · Location: ${cg(d.meta.location)}`:" · No location set"," · ","Last ",d.meta.periodDays," days"," · ","Generated ",lg(d.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(ug,{period:o,onChange:i}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:De(m),disabled:s,children:[e.jsx(lo,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(bg,{report:d}),e.jsx(Sg,{report:d,audience:"client"}),e.jsx(xg,{report:d}),e.jsx(jg,{report:d,audience:"client",projectName:t}),e.jsx(Ng,{report:d})]}):null}function ug({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:od.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 qi="AI Visibility — Server-Side",Oi="AI engine attention",mg=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,hg="Live telemetry from your server logs.";function xg({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ln,{eyebrow:Oi,title:qi,subtitle:hg}),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:Eu(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,o=wa(n,"requests",r),i=`${xt(s.verifiedCrawlerHits.current)} verified · ${xt(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,u=wa(s.aiUserFetchHits,"requests",r),m=wa(s.referralArrivals,"sessions",r),d=s.referralRedirects>0?`${xt(s.referralRedirects)} blocked by redirects`:"",p=[m,s.referralArrivalsClassSummary,d].filter(Boolean).join(" · "),h=s.byOperator.filter(j=>j.verifiedHits>0||j.unverifiedHits>0||j.userFetchHits>0||j.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ln,{eyebrow:Oi,title:qi,subtitle:mg(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Qa,{label:"AI bot requests observed",value:xt(n.current),subtitle:i}),e.jsx(Qa,{label:"AI user-fetch requests",value:xt(s.aiUserFetchHits.current),subtitle:u||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Qa,{label:"AI referral sessions",value:xt(s.referralArrivals.current),subtitle:p})]}),h.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:h.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:j.operator}),e.jsx("td",{children:xt(j.verifiedHits+j.unverifiedHits)}),e.jsx("td",{children:xt(j.userFetchHits)}),e.jsx("td",{children:xt(j.referralArrivals)})]},j.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 pg(t,s){return t.audience==="both"||t.audience===s}const gg={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function ha(t){return gg[t]??t.charAt(0).toUpperCase()+t.slice(1)}function fg(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 bg({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,r=a>0?`${s.mentionRate}%`:"—",o=a>0?`When customers asked AI ${a} ${a===1?"query":"queries"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer queries about your business.",i=fg(t.whatsChanged.mentionRate),u=n.providers.length>0?n.providers.map(ha).join(", "):`${xt(s.queryCount)} ${s.queryCount===1?"query":"queries"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:r}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:o}),i&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${i.tone==="positive"?"text-positive-400":i.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:i.arrow}),i.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(Ka,{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(Ka,{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(Ka,{label:"AI tools tested",value:xt(s.providerCount),subtitle:u})]}),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((m,d)=>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(d+1).padStart(2,"0")}),e.jsxs("span",{children:['"',m,'"']})]},d))})]}),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(m=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:ha(m.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(m.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[m.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",m.mentionedCount,"/",m.totalCount,")"]})]})]},m.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((m,d)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:m},d))})]})}function Ka({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 yg(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function vg(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function jg({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(h=>pg(h,s)),r=_u(t,a),o=s==="client",i=cd(),[u,m]=l.useState(new Set),d=u.size>0?r.filter(h=>!h.targetRef||!u.has(h.targetRef)):r,p=h=>{if(!h.targetRef)return;const j=h.targetRef;m(b=>new Set(b).add(j)),i.mutate({projectName:n,body:{targetRef:j}},{onSuccess:()=>{Ce({tone:"positive",title:`Dismissed "${h.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:b=>{Ce({tone:"negative",title:`Couldn't dismiss "${h.title}"`,detail:String(b)}),m(g=>{const f=new Set(g);return f.delete(j),f})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ln,{eyebrow:o?"Action plan":"Agency actions",title:o?"What to do next":"Agency Action Plan",subtitle:o?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),d.length===0?e.jsx(vr,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:d.map((h,j)=>{const b=h.evidence.length>0?h.evidence:h.why,g=h.why.length>0||h.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:j+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(de,{tone:ud(h),children:o?yg(h.horizon):dd(h.horizon)}),!o&&e.jsx(de,{tone:"neutral",children:md(h.category)}),e.jsx(de,{tone:"neutral",children:o?vg(h.confidence):`${hd(h.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:h.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:h.action}),e.jsx(Cg,{items:b,limit:3,className:"mt-3"}),g&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:o?"See the data behind this":"Evidence details"}),h.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:h.why.map((f,y)=>e.jsx("li",{children:f},y))})]}),h.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:h.evidence.map((f,y)=>e.jsx("li",{children:f},y))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:o?"What success looks like:":"Win condition:"})," ",h.successMetric]}),h.targetRef&&!te()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>p(h),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"})})]},`${h.priority}-${h.title}`)})})]})}function Gi({label:t,value:s,displayValue:n,max:a,barClass:r}){const o=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${o}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Ng({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=Uu(t).slice(0,5),o=s.length>0?Math.max(...s.map(m=>m.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(m=>m.impressions),1):0,u=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ln,{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."}),u?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(m=>e.jsx(Gi,{label:m.domain+(m.isCompetitor?" (competitor)":""),value:m.count,displayValue:`${xt(m.count)}×`,max:o,barClass:"bg-mono-400/70"},m.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:[xt(a.indexed)," of ",xt(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:xt(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:xt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:xt(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(m=>e.jsx(Gi,{label:m.query,value:m.impressions,displayValue:`${xt(m.impressions)} ${m.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},m.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer queries where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((m,d)=>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:m.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[xd(m.action),m.winnabilityClass==="ceded"&&e.jsx(de,{tone:"caution",children:"Ceded surface"})]})]},d))})]})]}):e.jsx(vr,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function br(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function yr(t){return t==="up"?"↑":t==="down"?"↓":"→"}function za({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"No prior data"})]});const a=n==="%"?"%":"",r=br(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:qu(s);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:yr(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Fi({label:t,delta:s,countLabel:n,comparisonWindowDays:a}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Not enough trend data"})]});const r=br(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=Ou(s,n,`vs prior ${a} days`);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[xt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:yr(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function wg({movements:t,audience:s}){const n=t.filter(r=>r.direction!=="flat");if(n.length===0)return null;const a=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:a?"How each AI tool changed":"AI engine movements"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a?"AI tool":"Engine"}),e.jsx("th",{children:a?"Was":"Prior"}),e.jsx("th",{children:a?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(r=>{const o=r.deltaAbs>0?"+":"",i=br(r.direction),u=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?ha(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:u,children:[o,r.deltaAbs.toFixed(1),"% ",yr(r.direction)]})]},r.provider)})})]})})]})}function _i({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const r=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!r&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:r?"What changed":"Title"}),e.jsx("th",{children:r?"Customer query":"Query"}),e.jsx("th",{children:r?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(o=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(de,{tone:og[o.severity],children:pd(o.severity)}),o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[o.title,r&&o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:o.query}),e.jsx("td",{className:"text-xs text-secondary",children:r?ha(o.provider):o.provider})]},o.id))})]})})]})}function Sg({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",r=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,o=e.jsx(Ln,{eyebrow:a?"Since last check":"Section 2",title:a?"What's different since last check":"What's Changed",subtitle:a?void 0:n.headline});return r?e.jsxs("section",{className:"page-section-divider",children:[o,e.jsx(vr,{message:a?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[o,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(za,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(za,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(za,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Fi,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Fi,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(wg,{movements:n.providerMovements,audience:s}),e.jsx(_i,{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(_i,{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 Qa({label:t,value:s,tone:n,subtitle:a}){const r=n==="positive"?"text-positive-400":n==="caution"?"text-caution-400":n==="negative"?"text-negative-400":"text-heading";return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function Ln({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 Cg({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),r=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((o,i)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:o},i)),r>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",r," more"]})]})}function vr({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function kg({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[u,m]=l.useState(null),[d,p]=l.useState(t.displayName),[h,j]=l.useState(t.canonicalDomain),[b,g]=l.useState(t.country),[f,y]=l.useState(t.language),[C,z]=l.useState(t.ownedDomains??[]),[L,R]=l.useState(""),[c,v]=l.useState(t.aliases??[]),[S,D]=l.useState(""),[T,N]=l.useState(null),[U,E]=l.useState(!1),[B,H]=l.useState(!1),[ge,ke]=l.useState(""),[_,se]=l.useState(""),[re,X]=l.useState(""),[Q,P]=l.useState(""),[G,Y]=l.useState(""),[J,W]=l.useState(null),[xe,V]=l.useState(null);l.useEffect(()=>{a||(p(t.displayName),j(t.canonicalDomain),g(t.country),y(t.language),z(t.ownedDomains??[]),v(t.aliases??[]))},[t,a]);function le(){r(!1),m(null),p(t.displayName),j(t.canonicalDomain),g(t.country),y(t.language),z(t.ownedDomains??[]),v(t.aliases??[]),R(""),D("")}function je(){const $=L.trim();$&&(C.includes($)||z([...C,$]),R(""))}function Fe($){z(C.filter(q=>q!==$))}function Le(){const $=S.trim();if(!$)return;const q=$.toLowerCase();c.some(me=>me.toLowerCase()===q)||v([...c,$]),D("")}function Ae($){v(c.filter(q=>q!==$))}async function Xe(){if(!(!d.trim()||!h.trim()||!b.trim()||!f.trim())){i(!0),m(null);try{await s(t.name,{displayName:d.trim(),canonicalDomain:h.trim(),ownedDomains:C,aliases:c,country:b.trim(),language:f.trim()}),r(!1),Ce({title:"Project settings saved",detail:`${d.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch($){m($ instanceof Error?$.message:"Failed to save")}finally{i(!1)}}}async function lt(){const $=ge.trim(),q=_.trim(),me=re.trim(),fe=Q.trim();if(!(!$||!q||!me||!fe)){E(!0),N(null);try{const Z={label:$,city:q,region:me,country:fe};G.trim()&&(Z.timezone=G.trim()),await bd(t.name,Z),n(),ke(""),se(""),X(""),P(""),Y(""),H(!1),Ce({title:"Location added",detail:`${$} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${$}`,dedupeMode:"drop"})}catch(Z){N(Z instanceof Error?Z.message:"Failed to add location")}finally{E(!1)}}}async function we($){E(!0),N(null);try{await fd(t.name,$),n(),Ce({title:"Location removed",detail:`${$} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${$}`,dedupeMode:"drop"})}catch(q){N(q instanceof Error?q.message:"Failed to remove location")}finally{E(!1)}}async function et($){E(!0),N(null);try{await gd(t.name,$),n(),Ce({title:"Default location updated",detail:`${$} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(q){N(q instanceof Error?q.message:"Failed to set default location")}finally{E(!1)}}async function Ve($){W($),V(null);try{await yd(t.name,$),Ce({title:`${$.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(q){V(q instanceof Error?q.message:"Could not download tracking results.")}finally{W(null)}}const _e=d!==t.displayName||h!==t.canonicalDomain||b!==t.country||f!==t.language||JSON.stringify(C)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(c)!==JSON.stringify(t.aliases??[]),Ue="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",Ie="mb-1 block text-sm font-medium text-secondary",F=ge.trim()&&_.trim()&&re.trim()&&Q.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!te()&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),u&&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:[u,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>m(null),children:"×"})]}),!te()&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Display name"}),e.jsx("input",{className:Ue,type:"text",value:d,onChange:$=>p($.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Canonical domain"}),e.jsx("input",{className:Ue,type:"text",value:h,onChange:$=>j($.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Country"}),e.jsx("input",{className:Ue,type:"text",value:b,onChange:$=>g($.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Language"}),e.jsx("input",{className:Ue,type:"text",value:f,onChange:$=>y($.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:C.map($=>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:[$,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Fe($),"aria-label":`Remove ${$}`,children:"×"})]},$))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ue} flex-1`,type:"text",placeholder:"docs.example.com",value:L,onChange:$=>R($.target.value),onKeyDown:$=>$.key==="Enter"&&($.preventDefault(),je())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!L.trim(),onClick:je,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,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:c.map($=>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:[$,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Ae($),"aria-label":`Remove ${$}`,children:"×"})]},$))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ue} flex-1`,type:"text",placeholder:"Facebook",value:S,onChange:$=>D($.target.value),onKeyDown:$=>$.key==="Enter"&&($.preventDefault(),Le())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!S.trim(),onClick:Le,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(A,{type:"button",disabled:o||!_e||!d.trim()||!h.trim(),onClick:De(Xe),children:o?"Saving...":"Save changes"}),e.jsx(A,{type:"button",variant:"outline",disabled:o,onClick:le,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($=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:$},$))}):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($=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:$},$))}):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:[T&&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:[T,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>N(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($=>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 ${$.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[$.label,$.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:$.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:$.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:$.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:$.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!te()&&$.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:U,onClick:()=>{et($.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${$.label} as default location`,children:"Set default"}),!te()&&e.jsx("button",{type:"button",disabled:U,onClick:()=>{we($.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${$.label}`,children:"Remove"})]})})]},$.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),te()?null:B?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:Ue,type:"text",value:ge,onChange:$=>ke($.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:Ue,type:"text",value:_,onChange:$=>se($.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:Ue,type:"text",value:re,onChange:$=>X($.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:Ue,type:"text",value:Q,onChange:$=>P($.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:Ue,type:"text",value:G,onChange:$=>Y($.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{type:"button",size:"sm",disabled:U||!F,onClick:De(lt),children:U?"Adding...":"Add location"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:U,onClick:()=>{H(!1),N(null)},children:"Cancel"})]})]}):e.jsx(A,{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(A,{type:"button",variant:"outline",size:"sm",disabled:J!==null,onClick:De(()=>Ve("csv")),children:J==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:J!==null,onClick:De(()=>Ve("json")),children:J==="json"?"Preparing JSON...":"Download JSON"})]})]}),xe&&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:xe})]})]})]})}function Cn(t){return{...t??{}}}function Ag(t,s){const n=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)),a=Object.entries(s).sort(([r],[o])=>r.localeCompare(o));return n.length===a.length&&n.every(([r,o],i)=>{const u=a[i];return u?.[0]===r&&u[1]===o})}function Pg({project:t,onSave:s}){const n=Re({queryKey:["settings"],queryFn:Yi,staleTime:6e4}),[a,r]=l.useState(t.providers.length===0),[o,i]=l.useState(t.providers),[u,m]=l.useState(()=>Cn(t.providerModels)),[d,p]=l.useState({providers:t.providers,providerModels:Cn(t.providerModels)}),[h,j]=l.useState(!1),[b,g]=l.useState(!1),[f,y]=l.useState(null),[C,z]=l.useState(null),L=l.useRef(null),R=n.data?.providerCatalog??[],c=l.useMemo(()=>new Set((n.data?.providers??[]).filter(B=>B.configured).map(B=>B.name)),[n.data]),v=l.useMemo(()=>{const B=new Map(R.map(H=>[H.name,H]));for(const H of Object.keys(u))B.has(H)||B.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[...B.values()].sort((H,ge)=>H.displayName.localeCompare(ge.displayName))},[R,u]),S=!Ag(u,d.providerModels);l.useEffect(()=>{if(h||b)return;const B={providers:t.providers,providerModels:Cn(t.providerModels)};p(B),r(B.providers.length===0),i(B.providers),m(B.providerModels)},[t]);function D(){g(!0),r(!1),o.length===0&&i([...c])}function T(B,H,ge=!1){g(!0),m(ke=>{const _={...ke};return H==="__inherit__"?delete _[B]:H==="__custom__"?_[B]=ge?"":_[B]??"":_[B]=H,_}),H==="__custom__"&&queueMicrotask(()=>L.current?.focus())}function N(B,H){g(!0),i(ge=>H?[...new Set([...ge,B])]:ge.filter(ke=>ke!==B))}function U(){g(!1),r(d.providers.length===0),i(d.providers),m(Cn(d.providerModels)),y(null),z(null)}async function E(){if(!(n.isError||n.isLoading||!a&&o.length===0)){j(!0),y(null),z(null);try{const B=Object.fromEntries(Object.entries(u).filter(([ge,ke])=>ke.trim()!==""&&(a||o.includes(ge)))),H={providers:a?[]:o,providerModels:B};await s(H),p({providers:[...H.providers],providerModels:Cn(H.providerModels)}),g(!1),z("Engine settings saved. They apply on the next sweep.")}catch(B){y(cr(B))}finally{j(!1)}}}return te()?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(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):R.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):c.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(fs,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":h,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:h,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{g(!0),r(!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:D})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:v.map(B=>{const H=o.includes(B.name),ge=c.has(B.name),ke=H&&!ge,_=u[B.name],se=B.knownModels.some(X=>X.id===_),re=_===void 0?"__inherit__":se?_:"__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:!ge&&!H,onChange:X=>N(B.name,X.target.checked)})," ",e.jsx("span",{children:B.displayName}),ke&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),H&&(B.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${B.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${B.name}`,value:re,onChange:X=>T(B.name,X.target.value,se),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",B.defaultModel||"default"]}),B.knownModels.map(X=>e.jsx("option",{value:X.id,children:X.displayName},X.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),re==="__custom__"&&e.jsx("input",{ref:L,"aria-label":`${B.displayName} custom model ID`,value:_??"",onChange:X=>{g(!0),m(Q=>({...Q,[B.name]:X.target.value}))},"aria-describedby":`project-model-hint-${B.name}`}),e.jsxs("p",{id:`project-model-hint-${B.name}`,className:"project-engine-help",children:[_?"Project override":"Inherited from instance settings",". ",B.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},B.name)})})]}),!a&&o.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),f&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:f}),C&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:C}),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(A,{type:"button",onClick:()=>{E()},disabled:h||!a&&o.length===0,children:h?"Saving engines…":"Save engines"}),e.jsx(A,{type:"button",variant:"outline",onClick:U,disabled:h,children:"Cancel"})]})]})}const Rg=[{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"}],Ui=["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 Ig({projectName:t}){const s=ks(),[n,a]=l.useState(!1),[r,o]=l.useState("daily"),[i,u]=l.useState(6),[m,d]=l.useState(""),[p,h]=l.useState("UTC"),[j,b]=l.useState(!1),[g,f]=l.useState(""),[y,C]=l.useState(!1),[z,L]=l.useState(!1),[R,c]=l.useState(null),[v,S]=l.useState(void 0),D=vd({client:K,path:{name:t}}),T=Re({...no({client:K,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),N=T.isPending||T.isFetching,U=T.isError,E=T.data?.find(G=>G.kind==="answer-visibility")??null,B=n&&v!==void 0&&(E?.updatedAt??null)!==v,H=G=>{s.setQueryData(D,Y=>{const J=(Y??[]).filter(W=>W.kind!=="answer-visibility");return G?[...J,G]:J})},ge=G=>{if(G){const Y=Sd(G.preset??null,G.cronExpr);o(Y.freq),u(Y.hour),d(Y.customCron);const J=Ui.includes(G.timezone);h(J?G.timezone:"Other"),b(!J),f(J?"":G.timezone)}else o("daily"),u(6),d(""),h("UTC"),b(!1),f("");S(G?.updatedAt??null)},ke=()=>{ge(E),c(null),a(!0)},_=()=>{ge(E),c(null)},se=async()=>{(await T.refetch()).isError?c("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):c(n?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},re=async(G,Y)=>{if(G instanceof en&&G.code==="SCHEDULE_VERSION_CONFLICT"){await se();return}c(G instanceof Error?G.message:Y)},X=async()=>{if(!(B||v===void 0)){C(!0),c(null);try{const G=await T.refetch();if(G.isError||G.data===void 0){c("Canonry could not verify the latest schedule. Try again before saving.");return}if(((G.data.find(V=>V.kind==="answer-visibility")??null)?.updatedAt??null)!==v)return;const W={timezone:j?g.trim()||"UTC":p,expectedUpdatedAt:v};r==="custom"?W.cron=m.trim():W.preset=wd(r,i);const xe=await Tr(t,W);a(!1),S(void 0),H(xe),Ce({title:"Schedule saved",detail:ja(xe.preset??null,xe.cronExpr,xe.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(G){await re(G,"Failed to save schedule")}finally{C(!1)}}},Q=async()=>{if(!E)return;const G=E.updatedAt;C(!0),c(null);try{const Y=await T.refetch();if(Y.isError||Y.data===void 0){c("Canonry could not verify the latest schedule. Try again before updating it.");return}const J=Y.data.find(V=>V.kind==="answer-visibility")??null;if(!J||J.updatedAt!==G){c("This schedule changed elsewhere. Review the latest version and try again.");return}const W={timezone:J.timezone,enabled:!J.enabled,expectedUpdatedAt:G};J.preset?W.preset=J.preset:W.cron=J.cronExpr;const xe=await Tr(t,W);H(xe),Ce({title:xe.enabled?"Schedule resumed":"Schedule paused",detail:ja(xe.preset??null,xe.cronExpr,xe.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(Y){await re(Y,"Failed to update schedule")}finally{C(!1)}},P=async()=>{if(!E)return;const G=E.updatedAt;L(!0),c(null);try{await Nd(t,G),H(null),a(!1),S(void 0),Ce({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(Y){await re(Y,"Failed to remove schedule")}finally{L(!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"})]}),!te()&&!N&&!U&&!n&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:ke,children:E?"Edit schedule":"+ Set schedule"})]}),N&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),R&&!n&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:R}),!N&&U&&e.jsxs(he,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{T.refetch()},children:"Retry"})]}),!N&&!U&&!n&&E===null&&e.jsx(he,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!N&&!U&&!n&&E!==null&&e.jsx(he,{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:ja(E.preset??null,E.cronExpr,E.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:E.cronExpr})]}),E.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(E.nextRunAt).toLocaleString()]}),E.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(E.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(de,{tone:E.enabled?"positive":"neutral",children:E.enabled?"Active":"Paused"}),!te()&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:y,onClick:De(Q),children:E.enabled?"Pause":"Resume"}),!te()&&e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:z,onClick:De(P),children:z?"Removing...":"Remove"})]})]})}),!te()&&n&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[B&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",role:"alert",children:[e.jsx("p",{children:"This schedule changed elsewhere. Load the latest version before saving."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:_,children:"Load latest schedule"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:r,onChange:G=>o(G.target.value),children:Rg.map(G=>e.jsx("option",{value:G.value,children:G.label},G.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:i,disabled:r==="twice-daily"||r==="custom",onChange:G=>u(parseInt(G.target.value)),children:Array.from({length:24},(G,Y)=>e.jsx("option",{value:Y,children:jd(Y)},Y))})]})]}),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:m,onChange:G=>d(G.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":p,onChange:G=>{G.target.value==="Other"?(b(!0),h("Other")):(b(!1),h(G.target.value))},children:[Ui.map(G=>e.jsx("option",{value:G,children:G},G)),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:G=>f(G.target.value)})]}),R&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:R}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),S(void 0),c(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:y||T.isFetching||U||B||r==="custom"&&!m.trim(),onClick:De(X),children:y?"Saving...":"Save schedule"})]})]})]})}const $g=[{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 Tg({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[u,m]=l.useState(["citation.lost","citation.gained"]),[d,p]=l.useState(!1),[h,j]=l.useState(null),[b,g]=l.useState({}),[f,y]=l.useState(new Set);l.useEffect(()=>{Cd(t).then(n).catch(()=>n([]))},[t]);const C=c=>{m(v=>v.includes(c)?v.filter(S=>S!==c):[...v,c])},z=async()=>{if(!(!o.trim()||u.length===0)){p(!0),j(null);try{const c=await kd(t,{channel:"webhook",url:o.trim(),events:u});n(v=>v==="loading"?[c]:[...v,c]),i(""),m(["citation.lost","citation.gained"]),r(!1),Ce({title:"Webhook added",detail:`Notifications will be sent to ${c.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(c){j(c instanceof Error?c.message:"Failed to add webhook")}finally{p(!1)}}},L=async c=>{if(!f.has(c)){y(v=>new Set(v).add(c));try{await Pd(t,c),n(v=>v==="loading"?v:v.filter(S=>S.id!==c)),Ce({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${c}`,dedupeMode:"drop"})}catch(v){j(v instanceof Error?v.message:"Failed to remove webhook")}finally{y(v=>{const S=new Set(v);return S.delete(c),S})}}},R=async c=>{g(v=>({...v,[c]:{state:"testing"}}));try{const v=await Ad(t,c);g(S=>({...S,[c]:{state:v.ok?"ok":"fail",status:v.status}})),v.ok&&Ce({title:"Test notification sent",detail:`Webhook returned status ${v.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${c}`,dedupeMode:"replace"})}catch{g(v=>({...v,[c]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),!te()&&s!=="loading"&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),j(null)},children:a?"Cancel":"+ Add webhook"})]}),!te()&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:o,onChange:c=>i(c.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:$g.map(c=>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:u.includes(c.value),onChange:()=>C(c.value)}),e.jsx("span",{className:"text-sm text-neutral",children:c.label})]},c.value))})]}),h&&e.jsx("p",{className:"text-negative-400 text-sm",children:h}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),j(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:d||!o.trim()||u.length===0,onClick:De(z),children:d?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(he,{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(c=>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:c.urlHost,children:c.urlDisplay??c.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:c.events.map(v=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:v.replace("."," ")},v))})}),e.jsx("td",{children:e.jsx(de,{tone:c.enabled?"positive":"neutral",children:c.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[b[c.id]&&(()=>{const v=b[c.id],S=v.state==="testing"?"Sending…":v.state==="ok"?`Delivered${v.status?` (${v.status})`:""}`:`Failed${v.status?` (${v.status})`:""}`;return e.jsx(de,{tone:v.state==="ok"?"positive":v.state==="fail"?"negative":"neutral",children:S})})(),!te()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:b[c.id]?.state==="testing",onClick:()=>{R(c.id)},children:"Test"}),!te()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:f.has(c.id),onClick:()=>{L(c.id)},children:f.has(c.id)?"Removing…":"Remove"})]})})]},c.id))})]}),h&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:h})]})]})}const Bi=2e3,Vi=3e5;function Mg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Lg(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 Dg({projectName:t,refreshNonce:s}){const n=ks(),[a,r]=l.useState(null),[o,i]=l.useState([]),[u,m]=l.useState(null),[d,p]=l.useState([]),[h,j]=l.useState([]),[b,g]=l.useState(null),[f,y]=l.useState(""),[C,z]=l.useState(""),[L,R]=l.useState(""),[c,v]=l.useState(!0),[S,D]=l.useState(!1),[T,N]=l.useState(null),[U,E]=l.useState("performance");l.useEffect(()=>{B()},[t,s]);async function B(){v(!0),N(null);try{const P=await n.fetchQuery({...ro({client:K,path:{name:t}}),staleTime:qt});if(r(P),P.connected){const[G,Y,J,W]=await Promise.all([n.fetchQuery({...au({client:K,path:{name:t}}),staleTime:qt}).catch(()=>null),n.fetchQuery({...ru({client:K,path:{name:t}}),staleTime:qt}).catch(()=>[]),n.fetchQuery({...iu({client:K,path:{name:t}}),staleTime:qt}).catch(()=>[]),P.siteUrl?Promise.resolve([]):n.fetchQuery({...ou({client:K,path:{name:t}}),staleTime:qt}).then(xe=>xe.sites).catch(()=>[])]);m(G),p(Y),j(J),i(W)}else m(null),p([]),j([]),i([])}catch(P){N(P instanceof Error?P.message:"Failed to load Bing data")}finally{v(!1)}}async function H(){if(C.trim()){N(null);try{const P=await lu(t,C.trim());await yt(n,"bing"),z(""),P.availableSites.length>0&&i(P.availableSites),await B()}catch(P){N(P instanceof Error?P.message:"Failed to connect")}}}async function ge(){try{await cu(t),await yt(n,"bing"),r(null),i([]),m(null),p([]),j([]),g(null),R(""),N(null)}catch(P){N(P instanceof Error?P.message:"Failed to disconnect")}}async function ke(){if(L)try{await du(t,L),await yt(n,"bing"),await B()}catch(P){N(P instanceof Error?P.message:"Failed to set site")}}async function _(){if(f.trim())try{const P=await uu(t,f.trim());await yt(n,"bing"),g(P),p(G=>[P,...G])}catch(P){N(P instanceof Error?P.message:"Inspection failed")}}async function se(P){D(!0),N(null);try{const G=await Lr(t,{urls:[P]}),{succeeded:Y,failed:J,total:W}=G.summary;Ce({title:"Bing submission requested",detail:J===0?`${Y} URL submitted to Bing.`:`${Y}/${W} submitted successfully, ${J} failed.`,tone:J===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}catch(G){const Y=G instanceof Error?G.message:"Submission failed";N(Y),Ce({title:"Bing submission failed",detail:Y,tone:"negative",dedupeKey:`bing:indexing:${t}:${P}`,dedupeMode:"replace"})}finally{D(!1)}}async function re(){D(!0),N(null),Ce({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const P=await Lr(t,{allUnindexed:!0}),{succeeded:G,failed:Y,total:J}=P.summary;Ce({title:"Bing submissions requested",detail:Y===0?`${G}/${J} URL${J!==1?"s":""} submitted to Bing.`:`${G}/${J} submitted successfully, ${Y} failed.`,tone:Y===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(P){const G=P instanceof Error?P.message:"Batch submission failed";N(G),Ce({title:"Bing submissions failed",detail:G,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{D(!1)}}if(c)return e.jsx(he,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return te()?e.jsxs(he,{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(de,{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(he,{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(de,{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:C,onChange:P=>z(P.target.value),onKeyDown:P=>{P.key==="Enter"&&H()}}),e.jsx(We,{size:"sm",disabled:!C.trim(),onClick:De(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"})]})]}),T&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:T})]});if(!a.siteUrl)return e.jsxs(he,{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(de,{tone:"positive",children:"Connected"}),!te()&&e.jsx(We,{size:"sm",variant:"ghost",onClick:De(ge),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Bt(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),o.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:L,onChange:P=>R(P.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map(P=>e.jsxs("option",{value:P.url,children:[P.url,P.verified?" (verified)":""]},P.url))]}),!te()&&e.jsx(We,{size:"sm",disabled:!L,onClick:De(ke),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."})]})]}),T&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:T})]});const X=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],Q=X.find(P=>P.key===U)??X[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(he,{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(de,{tone:"positive",children:"Connected"}),!te()&&e.jsx(We,{size:"sm",variant:"ghost",onClick:De(ge),children:"Disconnect"})]})]}),T&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:T}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["This project uses ",e.jsx("code",{children:a.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Bt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:Q.eyebrow}),e.jsx("h3",{children:Q.title})]}),e.jsx("p",{className:"text-xs text-muted",children:u?.lastInspectedAt?`Last inspected ${Bt(u.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:X.map(P=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${U===P.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>E(P.key),children:P.label},P.key))}),U==="coverage"&&u&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(_n,{label:"Indexed",value:u.summary.indexed,tone:"positive"}),e.jsx(_n,{label:"Not in index",value:u.summary.notIndexed+(u.summary.unknown??0),tone:"negative"}),e.jsx(_n,{label:"Status unknown",value:u.summary.unknown??0,tone:"neutral"}),e.jsx(_n,{label:"Coverage",value:`${u.summary.percentage}%`,tone:"neutral"})]}),u.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 (",u.notIndexed.length,")"]}),!te()&&e.jsx(We,{size:"sm",variant:"ghost",disabled:S,onClick:De(re),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!te()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:u.notIndexed.map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.httpCode??"—"}),!te()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{se(P.url)},children:"Submit"})})]},P.id))})]})})]}),(u.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 (",(u.unknown??[]).length,")"]}),!te()&&e.jsx(We,{size:"sm",variant:"ghost",disabled:S,onClick:De(re),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!te()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(u.unknown??[]).map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.lastCrawledDate?Bt(P.lastCrawledDate):"—"}),!te()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{se(P.url)},children:"Submit"})})]},P.id))})]})})]}),u.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",u.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:u.indexed.map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.lastCrawledDate?Bt(P.lastCrawledDate):"—"})]},P.id))})]})})]})]}),U==="coverage"&&!u&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),U==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!te()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:f,onChange:P=>y(P.target.value),onKeyDown:P=>{P.key==="Enter"&&_()}}),e.jsx(We,{size:"sm",disabled:!f.trim(),onClick:De(_),children:"Inspect"})]}),b&&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:b.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:b.inIndex?"text-positive-400":"text-negative-400",children:b.inIndex?"Yes":"No"})," · ","HTTP: ",b.httpCode??"—"," · ","Crawled: ",b.lastCrawledDate??"—"]})]}),d.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:d.map(P=>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:P.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(de,{tone:P.inIndex?"positive":"negative",children:P.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:P.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Bt(P.inspectedAt)})]},P.id))})]})})]}),U==="performance"&&e.jsx("div",{className:"mt-4",children:h.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:Fn[Ys.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Fn[Ys.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Fn[Ys.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Fn[Ys.Position]})]})}),e.jsx("tbody",{children:h.map((P,G)=>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:P.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:P.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:P.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(P.ctr)?P.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:P.averagePosition.toFixed(1)})]},G))})]})})})]})]})}function Eg({projectName:t}){const s=ks(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,u]=l.useState("idle"),[m,d]=l.useState(null),p=l.useRef(null),[h,j]=l.useState(null),[b,g]=l.useState(null),[f,y]=l.useState(0);async function C(L=!1){L||o(!0),d(null);try{const[R,c]=await Promise.all([s.fetchQuery({...lr({client:K,path:{name:t}}),staleTime:qt}).catch(()=>[]),s.fetchQuery({...ro({client:K,path:{name:t}}),staleTime:qt}).catch(()=>null)]),v=R.find(S=>S.connectionType==="gsc")??null;j(v),g(c)}catch(R){d(R instanceof Error?R.message:"Failed to load search engine connections")}finally{o(!1)}}async function z(){if(i!=="idle")return;p.current?.abort();const L=new AbortController;p.current=L;const R=L.signal;u("syncing"),d(null),Ce({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const c=[],v=[];try{async function S(){if(!h)return;const N=await su(t);if(!N?.id)return;const U=Date.now()+Vi;for(;Date.now()<U;){if(R.aborted||(await new Promise(B=>setTimeout(B,Bi)),R.aborted))return;const E=await Wa(N.id).catch(()=>null);if(!E)break;if(["completed","failed","cancelled"].includes(E.status)){E.status!=="completed"&&c.push(`Google sync ${E.status}`);return}}v.push("Google sync is still running — search data will appear shortly")}async function D(){if(!b?.connected)return;const N=await nu(t).catch(()=>null);if(!N?.id){c.push("Bing sweep could not be started");return}const U=Date.now()+Vi;for(;Date.now()<U;){if(R.aborted||(await new Promise(B=>setTimeout(B,Bi)),R.aborted))return;const E=await Wa(N.id).catch(()=>null);if(!E)break;if(["completed","failed","cancelled","partial"].includes(E.status)){E.status==="failed"?c.push("Bing sweep failed"):E.status==="partial"&&v.push("Bing sweep finished with some pages unverified");return}}v.push("Bing sweep is still running — coverage will update shortly")}const T=await Promise.allSettled([S(),D()]);for(const N of T)N.status==="rejected"&&c.push(N.reason instanceof Error?N.reason.message:"Sync failed");if(await Promise.all([yt(s,"gsc"),yt(s,"bing")]),R.aborted)return;if(u("reloading"),await C(!0),y(N=>N+1),c.length>0){const N=`Partial refresh: ${[...c,...v].join("; ")}`;d(N),Ce({title:"Search coverage partially refreshed",detail:N,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else v.length>0?Ce({title:"Search coverage refresh incomplete",detail:v.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Ce({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(!R.aborted){const D=S instanceof Error?S.message:"Refresh failed";d(D),Ce({title:"Search coverage refresh failed",detail:D,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{R.aborted||u("idle")}}return l.useEffect(()=>(C(),()=>{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(([L,R])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===L,className:`project-subnav-link ${n===L?"project-subnav-link-active":""}`,onClick:()=>a(L),children:R},L))}),!te()&&e.jsxs(We,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{z()},children:[e.jsx(ra,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),m&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:m}),n==="google"&&e.jsx(Um,{projectName:t,refreshNonce:f}),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(Dg,{projectName:t,refreshNonce:f})]})]})}function xa({label:t,summary:s,displayValue:n,tooltip:a}){const r=s.value.trim()!==""&&Number.isFinite(Number(s.value)),o=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(ze,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${zi[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,r?e.jsx("span",{className:"text-faint",children:"%"}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${o}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function qg({model:t,sweepRunning:s,hasVisibilityBaseline:n}){const a=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,i=t.recentRuns.find(b=>b.kind===Gs["answer-visibility"]&&(b.status===aa.completed||b.status===aa.partial)),u=b=>b.tone==="positive"?"improved":b.tone==="negative"?"declined":b.gained>0||b.lost>0?"mixed":"steady",m=u(r),d=u(a),p=(()=>{if(s)return"A fresh sweep is running now";if(!n)return"No AI Visibility baseline yet";if(!o.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(o.querySetChanged)return"Tracking scope changed since the previous sweep";if(m===d)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 b=m==="mixed"?"Answer mention movement was mixed":m==="steady"?"Answer mentions held steady":`Answer mentions ${m}`,g=d==="mixed"?"citation movement was mixed":d==="steady"?"citation coverage held steady":`citation coverage ${d}`;return`${b}; ${g}`})(),h=[o.addedQueryCount>0&&`${o.addedQueryCount} ${o.addedQueryCount===1?"query":"queries"} added`,o.removedQueryCount>0&&`${o.removedQueryCount} ${o.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),j=`${o.comparableQueryCount} comparable ${o.comparableQueryCount===1?"query":"queries"}`;return e.jsxs("section",{className:"overview-brief","aria-labelledby":"overview-brief-title",children:[e.jsxs("div",{className:"overview-brief-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft",children:["Visibility",e.jsx(ze,{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:p})]}),i?e.jsxs("p",{className:"overview-brief-updated",children:["Updated ",i.startedAt]}):null]}),n?e.jsxs("div",{className:"overview-brief-grid",children:[e.jsxs("div",{className:"overview-brief-panel overview-brief-coverage",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage now"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(xa,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(xa,{label:"Cited",summary:t.visibilitySummary})]}),t.mentionSummary.providerCoverage&&e.jsxs("p",{className:"overview-brief-note",children:["Partial sweep: ",t.mentionSummary.providerCoverage]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Since last sweep"}),o.hasPreviousRun?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overview-signal-change-list",children:[e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Mentioned"}),r.gained===0&&r.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[r.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",r.gained]}),r.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",r.lost]})]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),a.gained===0&&a.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[a.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",a.gained]}),a.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",a.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${o.querySetChanged?"text-caution-400/80":""}`,children:o.querySetChanged?`${h||"Query set changed"} · ${j}.`:`${j}.`})]}):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."})]})]})]}):e.jsx("div",{className:"overview-brief-grid",children:e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage signals"}),e.jsxs("dl",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Mentioned"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your brand or domain appears in the answer text."})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Cited"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your domain appears in the engine's source list."})]})]}),e.jsx("p",{className:"mt-4 border-t border-subtle pt-4 text-sm font-medium text-strong",children:s?"Your first sweep is running. Results will appear when it completes.":"Complete your first AI Visibility sweep to measure both signals."})]})})]})}function Ha({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:o}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:r||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(oa,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function Zg(t){const{projectName:s}=sl({from:"/projects/$projectName"}),a=ao()?.dashboard.projects.find(b=>b.project.name===s||b.project.id===s)?.project.name??null,r=Re({...Rd({client:K}),enabled:!a}),o=a??r.data?.find(b=>b.name===s||b.id===s)?.name??null,{commandCenter:i,isLoading:u,latestVisibilityRevision:m,competitorHistoryRevision:d,refetch:p}=Id(o),h=!a&&r.isLoading||u;return!o&&!a&&r.isSuccess&&!u?e.jsx("div",{className:"page-container",children:e.jsxs(he,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(A,{asChild:!0,children:e.jsx(fs,{to:"/",children:"Return to overview"})})]})}):!i||h?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(b=>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"})]},b))}),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(b=>e.jsx("div",{className:"skeleton-text-sm w-full"},b))})]})]}):e.jsx(Gg,{model:i,refetch:p,latestVisibilityRevision:m,competitorHistoryRevision:d,...t})}function Og({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const i=m=>{r.current&&!r.current.contains(m.target)&&a(!1)},u=m=>{m.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",i),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const o=t.some(i=>i.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${o?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(i=>!i),children:["More",e.jsx(oa,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(i=>e.jsx(fs,{to:i.href,role:"menuitem",className:`project-subnav-menu-item ${i.key===s?"project-subnav-menu-item-active":""}`,"aria-current":i.key===s?"page":void 0,onClick:()=>a(!1),children:i.label},i.key))}):null]})}function Gg({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r}){const o=nl(),i=ks(),{canWrite:u}=so(),m=ao(),d=s.project.name,p=Re({...$d({client:K,path:{name:d}}),enabled:!te()&&!!d&&(u||t==="portfolio"||t==="overview"||t==="settings"),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),h=m?m.dashboard.settings.providerStatuses.filter(k=>k.state==="ready").map(k=>Mr(k.name)):void 0,j=p.data?.answerVisibilityProviderReady,b=h,g=s.project.providers.map(Mr),f=b?.some(k=>g.length===0||g.includes(k))===!0,y=g.length===0||g.includes(Td),C=Re({...Md({client:K}),enabled:!te()&&u&&j===void 0&&y&&!f,staleTime:6e4,retry:!1}),z=y?C.isSuccess?typeof C.data.browserVersion=="string":C.isError?!1:void 0:!1,L=j??Ld({projectProviders:g,configuredApiProviders:b,cdpConfigured:z}),R=l.useMemo(()=>{const k=Dd();return k?Ed(k.projectTabs):void 0},[]),c=qd(t,R),v=l.useMemo(()=>s.competitors.map(k=>k.domain),[s.competitors]),[S,D]=l.useState(!1),[T,N]=l.useState(!1),U=Od(),E=al({strict:!1}),B=E.manageQueries===!0,H=l.useCallback(()=>{o({to:".",replace:!0,search:k=>({...k,siteHealthRunId:void 0})})},[o]),[ge,ke]=l.useState(B),[_,se]=l.useState(""),[re,X]=l.useState(!1),[Q,P]=l.useState(null),[G,Y]=l.useState("30d"),[J,W]=l.useState(void 0),[xe,V]=l.useState(!1),[le,je]=l.useState(null),[Fe,Le]=l.useState(!1),Ae=Qu(E),[Xe,lt]=l.useState(void 0),[we,et]=l.useState(void 0),Ve=l.useCallback(k=>{lt(k.search),k.sort&&et(k.sort),o({to:".",search:ce=>({...ce,...Wu(k)}),replace:!1})},[o]),[_e,Ue]=l.useState(!1),Ie=s?.visibilityEvidence??[],F=s?.project.displayName||s?.project.name||d,$=Gd(),q=Re({...Fd({client:K,path:{name:d}}),enabled:c==="portfolio"&&!!d,staleTime:0,refetchOnMount:"always"}),me=Re({..._d({client:K,path:{name:d}}),enabled:!te()&&!!d&&(u||c==="portfolio"||c==="overview"||c==="settings"),staleTime:0,refetchOnMount:"always"}),fe=me.data?.active??null,Z=me.data!==void 0,Ze=new Set(fe&&Number(fe.plan.schemaVersion)===2?fe.plan.groups?.map(k=>k.stableKey)??[]:[]),Ye={...Ae.scope==="group"&&!!Ae.groupKey&&Z&&!Ze.has(Ae.groupKey)?{scope:"all",queryClass:Ae.queryClass}:Ae,...Xe?{search:Xe}:{}},$e=fe===null?null:Number(fe.plan.schemaVersion),Te=fe?.revision??0,pt=Z?`${d}:${Te}`:null,ct=l.useRef(null);l.useEffect(()=>{const k=ct.current;pt!==null&&(ct.current=pt),Hu(k,pt)&&(Ve({scope:"all",queryClass:"all"}),Ue(!1))},[pt,Ve]);const Oe={client:K,path:{name:d},query:{scope:Ye.scope,...Ye.groupKey?{groupKey:Ye.groupKey}:{},queryClass:Ye.queryClass,...Ye.search?{search:Ye.search}:{},...we?{sort:we}:{},limit:50}},Qe=rl({...Ud(Oe),enabled:c==="overview"&&!!d&&$e===2,initialPageParam:Oe,getNextPageParam:(k,ce)=>{if(!k.properties.nextCursor)return;const Ne=ce[0]?.measurement.displayedRunId;return{path:Oe.path,query:{...Oe.query,cursor:k.properties.nextCursor,...Ne?{runId:Ne}:{}}}},placeholderData:Ki,staleTime:0,refetchOnMount:"always"}),vt=Qe.data?.pages[0]?.measurement.displayedRunId,Ke=Re({...Bd({client:K,path:{name:d},query:{revision:Te,...vt?{runId:vt}:{}}}),enabled:c==="overview"&&!!d&&fe!==null&&($e===1||_e&&vt!==void 0),staleTime:0,refetchOnMount:"always"}),Ee=me.data!==void 0,qe=q.data!==void 0,jt=me.isPending&&!Ee,Ge=me.isError&&!Ee,It=q.isPending&&!qe,Gt=q.isError&&!qe,gt=Ke.data!==void 0,kt=Xp({activePlanSchemaVersion:p.data?.activeSchemaVersion??$e,hasDraft:p.data?.draft!==null&&p.data?.draft!==void 0}),ht=p.data===void 0&&me.data===void 0&&(me.isLoading||p.isLoading),O=$e===2&&Ye.scope==="group"?Ye.groupKey:void 0,Se=$e===2&&Ye.scope==="all",be=l.useMemo(()=>{if(!(fe?.plan.schemaVersion!==2||!O))return fe.plan.groups.find(k=>k.stableKey===O)},[fe,O]),ve={client:K,path:{name:d},query:{window:G,queryClass:$e===2?Ye.queryClass:"non-brand",...O?{groupKey:O}:{},...Se?{scope:"all-markets"}:{}}},ft=c==="overview"&&!!d&&!ht,Je=Re({...Vd(ve),enabled:ft,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});Kd(d,JSON.stringify([r,s.competitors.map(k=>k.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,Te,p.data?.draft?.etag??null]),ft);const At=Je.isError?Je.data===void 0?"Could not load competitor history. Your pinned competitors remain available.":"Could not refresh competitor history. Showing the last available data.":void 0,Nt=l.useMemo(()=>s.competitors.map(k=>({domain:k.domain,label:k.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:k.citationCount,answeredResults:k.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),rs=l.useMemo(()=>{if(fe?.plan.schemaVersion!==2)return Nt;const k=O?be?.competitors??[]:fe.plan.groups.flatMap(Ne=>Ne.competitors),ce=new Map;for(const Ne of k){const _t=Ne.domain.trim().toLowerCase();!_t||ce.has(_t)||ce.set(_t,{domain:Ne.domain,label:Ne.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const Ne of Nt){const _t=Ne.domain.trim().toLowerCase();!_t||ce.has(_t)||ce.set(_t,Ne)}return[...ce.values()]},[fe,O,Nt,be]),is=$e===2?rs:Nt,cs=Et({...zd({client:K}),meta:{skipGlobalErrorToast:!0}}),rt=p.data!==void 0?"success":p.isError?"error":"pending",ds=l.useMemo(()=>{const k=Qe.data?.pages;return k?!$u(k):!1},[Qe.data]),dt=l.useMemo(()=>{const k=Qe.data?.pages,ce=k?.[0],Ne=k?.at(-1);if(!(!ce||!Ne||ds))return{...ce,properties:{...ce.properties,items:k.flatMap(_t=>_t.properties.items),nextCursor:Ne.properties.nextCursor}}},[ds,Qe.data]),bs=l.useMemo(()=>{if(fe)return fe.plan.schemaVersion===1?Ke.data?ig(fe,Ke.data):void 0:dt?Tu({overview:dt,activePlan:fe,sort:we,report:Ke.data,reportState:dt.measurement.displayedRunId===void 0?"ready":Ke.isFetching&&Ke.data===void 0?"loading":Ke.isError&&Ke.data===void 0?"error":Ke.data?"ready":"loading"}):void 0},[fe,Ke.data,Ke.isError,Ke.isFetching,dt]),Wt=$e===2?ds?"error":Qe.isPending?"loading":Qe.isError&&bs===void 0?"error":"ready":Ke.isPending&&!gt?"loading":Ke.isError&&!gt?"error":"ready",zt=(s?.recentRuns??[]).some(k=>k.kind===Gs["answer-visibility"]&&(k.status===aa.running||k.status===aa.queued)),Yt=s.queryCounts.total>0,wt=l.useMemo(()=>(s?.project.locations??[]).map(k=>k.label),[s?.project.locations]),us=l.useMemo(()=>new Set(Ie.map(k=>k.location??"")),[Ie]),Qt=us.has(""),bt=l.useMemo(()=>[...new Set(Ie.map(k=>k.query))].sort((k,ce)=>k.localeCompare(ce)),[Ie]),ys=bt.length>0||s.queryCounts.total>0,ms=ys||fe!==null,hs=u&&!ys&&me.data===void 0&&me.isPending,xs=u&&p.isError&&!p.isFetching,St=u&&!xs&&(hs||L===void 0||p.isFetching),ee=u&&!St&&!(!St&&ms&&L===!0),ne=Re({...no({client:K,path:{name:d}}),enabled:!te()&&!!d,retry:!1}).data?.find(k=>k.kind===Gs["answer-visibility"]),ie=ne?.enabled&&ne.nextRunAt?`Next AI sweep ${new Date(ne.nextRunAt).toLocaleString()}`:null,Me=l.useMemo(()=>{const k=[...us].filter(Boolean);return k.length>1?k:wt},[us,wt]);l.useEffect(()=>{if(J===void 0||J===""||!d){je(null),Le(!1);return}Le(!0),Qd(d,J,20).then(k=>{je(k),Le(!1)}).catch(()=>{je(null),Le(!1)})},[J,d]);const $t=l.useMemo(()=>{if(!le)return null;const k=new Map;for(const ce of le){for(const[Ne,_t]of Object.entries(ce.providerRuns??{}))k.set(`${ce.query}::${Ne}`,_t.map(Ut=>({runId:Ut.runId,citationState:Ut.citationState,createdAt:Ut.createdAt,answerMentioned:Ut.answerMentioned,visibilityState:Ut.visibilityState,visibilityTransition:Ut.visibilityTransition,mentionState:Ut.mentionState,mentionTransition:Ut.mentionTransition})));(!ce.providerRuns||Object.keys(ce.providerRuns).length===0)&&k.set(`${ce.query}::`,ce.runs.map(Ne=>({runId:Ne.runId,citationState:Ne.citationState,createdAt:Ne.createdAt,answerMentioned:Ne.answerMentioned,visibilityState:Ne.visibilityState,visibilityTransition:Ne.visibilityTransition,mentionState:Ne.mentionState,mentionTransition:Ne.mentionTransition})))}return k},[le]),ut=l.useMemo(()=>{const k=J!==void 0?Ie.filter(ce=>J===""?!ce.location:ce.location===J):Ie;return $t?k.map(ce=>{const Ne=$t.get(`${ce.query}::${ce.provider}`)??$t.get(`${ce.query}::`);return Ne?{...ce,runHistory:Ne}:ce}):k},[Ie,J,$t]);async function As(){try{await $.mutateAsync({projectName:d,projectLabel:F,sourceAction:"project-run"}),n()}catch{}}function w(){o({to:"/setup",search:{experience:"legacy",setupProject:d}})}async function oe(){N(!0);try{await tu(d),Ce({title:"Project deleted",detail:`${F} was removed.`,tone:"positive",dedupeKey:`project:delete:${d}`,dedupeMode:"drop"}),o({to:"/"}),n()}catch(k){console.error("Failed to delete project:",k)}finally{N(!1)}}async function at(){const k=_.split(`
|
|
8
|
+
`).map(ce=>ce.trim()).filter(Boolean);if(k.length!==0){X(!0);try{await Jd(d,k),n(),se("")}finally{X(!1)}}}async function Pe(k){P(k);try{await Yd(d,[k]),n()}catch(ce){Ce({title:"Could not remove query",detail:ce instanceof Error?ce.message:`Failed to remove "${k}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{P(null)}}async function it(k){const ce=k.trim();if(!ce)return!1;try{return await Hd(d,[ce]),n(),!0}catch(Ne){return Ce({title:"Could not add competitor",detail:Ne instanceof Error?Ne.message:`Failed to add ${ce}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function Jt(k){const ce=s.competitors.find(Ne=>Ne.domain===k);if(!ce)return Ce({title:"Could not remove competitor",detail:`Could not find ${k} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await Wd(d,ce.id),n(),!0}catch(Ne){return Ce({title:"Could not remove competitor",detail:Ne instanceof Error?Ne.message:`Failed to remove ${ce.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function Tt(k){const ce=k.trim();if(!ce||!O||$e!==2||!u||te()||cs.isPending)return!1;try{const Ne=await cs.mutateAsync({client:K,path:{name:d},headers:{"Idempotency-Key":Mg()},body:{expectedActiveRevision:Te,groupKey:O,domain:ce}});return Promise.allSettled([p.refetch()]),Ce({title:Ne.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${ce} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${O}:${ce}`,dedupeMode:"replace"}),!0}catch(Ne){return Ce({title:"Could not add market competitor",detail:Ne instanceof Error?Ne.message:`Failed to add ${ce} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function Ft(k,ce){const Ne=await Xd(k,ce);return await i.invalidateQueries({queryKey:to({client:K})}),i.setQueryData(Zd({client:K,path:{name:k}}),Ne),Lg(i,Ne),ce.providers!==void 0&&await i.invalidateQueries({queryKey:eu({client:K,path:{name:k}}),exact:!0}),Ne}const Ht=`/projects/${encodeURIComponent(s.project.name)}`,Mt=[{key:"overview",label:"AI Visibility",href:Ht},{key:"search-console",label:"Search Engines",href:`${Ht}/search-console`},{key:"activity",label:"Activity",href:`${Ht}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Ht}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Ht}/conversions`},{key:"local",label:"Local Presence",href:`${Ht}/local`},{key:"discovery",label:"Query Discovery",href:`${Ht}/discovery`},{key:"backlinks",label:"Backlinks",href:`${Ht}/backlinks`}],vs=[{key:"report",label:"Report",href:`${Ht}/report`},{key:"history",label:"Change History",href:`${Ht}/history`}],vn=Mt.filter(k=>Na(k.key,R)),qn=vs.filter(k=>Na(k.key,R)),ln=Na("settings",R)?{key:"settings",label:"Settings",href:`${Ht}/settings`}:null;return e.jsxs("div",{className:"page-container",children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]}),!te()&&e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map(k=>e.jsx("span",{className:"tag",children:k},k))]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!te()&&e.jsxs("div",{className:"flex items-center gap-3",children:[ie?e.jsx("p",{className:"text-sm text-secondary",children:ie}):null,e.jsx(We,{type:"button",variant:"outline",disabled:$.isPending||zt||St,onClick:xs?()=>{p.refetch()}:ee?w:De(As),children:$.isPending?"Starting…":zt?"AI sweep running…":St?"Checking AI readiness…":xs?"Retry AI readiness":ee?"Set up AI Visibility":"Run AI sweep"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[vn.map(k=>e.jsx(fs,{to:k.href,className:`project-subnav-link ${k.key===c?"project-subnav-link-active":""}`,"aria-current":k.key===c?"page":void 0,children:k.label},k.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Og,{items:qn,activeTab:c}),ln&&e.jsx(fs,{to:ln.href,className:`project-subnav-link ${c==="settings"?"project-subnav-link-active":""}`,"aria-current":c==="settings"?"page":void 0,children:ln.label},ln.key)]})]}),c==="portfolio"&&!te()?e.jsx(Mp,{projectName:d,canEdit:u,queries:q.data??[],isQueryLoading:It,isQueryError:Gt,onRetryQueries:()=>{q.refetch()},publishedPlan:fe,onCreateQueries:async k=>(await U.mutateAsync({projectName:d,queries:[...k]}),(await q.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{o({to:"/projects/$projectName",params:{projectName:d},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([p.refetch(),me.refetch()]).finally(()=>{o({to:"/projects/$projectName",params:{projectName:d}})})}},d):c==="overview"?ht?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(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{me.refetch()},children:"Retry setup check"})]}):null,e.jsx(Zp,{mode:kt,canEdit:u&&!te()&&!jt&&!Ge,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Yh,{projectName:s.project.name,competitorDomains:v,analyticsRevision:a})}),e.jsx(qg,{model:s,sweepRunning:zt,hasVisibilityBaseline:Yt}),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"}),e.jsx("p",{className:"supporting-copy",children:"Latest measured results against pinned competitors."})]})}),Yt?e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(em,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:v},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(xa,{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(xa,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was cited as a source but you were not."})]})})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Competitive mention and citation gaps appear after the first AI Visibility sweep."})]}),e.jsx("section",{className:"page-section-divider",children:e.jsx(Or,{window:G,landscape:Je.data,pinnedFallback:Nt,canWrite:u,isEmbed:te(),onWindowChange:Y,onPin:u&&!te()?it:void 0,onUnpin:u&&!te()?Jt:void 0,onAddCompetitor:u&&!te()?it:void 0,error:At,onRetry:ft?()=>{Je.refetch()}:void 0,isLoading:ft&&Je.isPending&&Je.data===void 0})}),e.jsxs(Ha,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!te()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(We,{type:"button",variant:"outline",size:"sm",onClick:()=>ke(!ge),children:ge?"Done":"Manage queries"})}),!te()&&ge&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[bt.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:bt.map(k=>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:k,children:k}),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 ${k}`,title:`Stop tracking "${k}"`,disabled:Q!==null,onClick:()=>{Pe(k)},children:Q===k?"Removing…":"Remove"})]},k))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:_,onChange:k=>se(k.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[_.split(`
|
|
9
|
+
`).filter(k=>k.trim()).length," to add"]}),e.jsx(We,{type:"button",size:"sm",disabled:!_.trim()||re,onClick:De(at),children:re?"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 ${J===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":J===void 0,onClick:()=>{W(void 0)},children:"All locations"}),s.project.locations.map(k=>e.jsx("button",{className:`filter-chip ${J===k.label?"filter-chip-active":""}`,type:"button","aria-pressed":J===k.label,onClick:()=>{W(k.label),V(!1)},children:k.label},k.label)),Qt&&e.jsx("button",{className:`filter-chip ${J===""?"filter-chip-active":""}`,type:"button","aria-pressed":J==="",onClick:()=>{W(""),V(!1)},children:"No location"}),Me.length>1&&J===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${xe?"filter-chip-active":""}`,type:"button","aria-pressed":xe,onClick:()=>V(k=>!k),title:"Side-by-side location comparison",children:"Compare"})]}),e.jsx(mm,{evidence:ut,compareLocations:xe})]}),e.jsxs(Ha,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:te(),children:[e.jsx(ph,{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(ze,{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(k=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx($n,{provider:k.provider}),k.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:k.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[k.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[k.cited," of ",k.total]})]},`${k.provider}::${k.model??"unknown"}`))})]})})]})]}),!te()&&e.jsx(Ha,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(k=>e.jsx(mu,{run:k},k.id))})})]}),report:bs,reportState:Wt,onOpenSetup:te()?void 0:()=>{o({to:"/projects/$projectName/portfolio",params:{projectName:d}})},onRetryReport:()=>{$e===2?Promise.all([Qe.refetch(),Ke.refetch()]):Ke.refetch()},onViewChange:k=>{Ve({scope:k.scope,...k.groupKey?{groupKey:k.groupKey}:{},queryClass:k.queryClass,...k.search?.trim()?{search:k.search.trim()}:{}})},onLoadMore:k=>{k===dt?.properties.nextCursor&&Qe.fetchNextPage()},onPropertyExpand:()=>{_e&&Ke.isError&&Ke.refetch(),Ue(!0)},onRetryEvidence:()=>{Ke.refetch()},renderPropertyLink:$e===2&&!te()?({id:k,name:ce})=>e.jsx(fs,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:d,targetKey:k},className:"text-link hover:underline",children:ce}):void 0,isViewLoading:Qe.isPlaceholderData,isLoadingMore:Qe.isFetchingNextPage,isLoadMoreError:Qe.isFetchNextPageError,viewSearch:Ye.search??""},`${d}:${Te}`),kt.surface!=="simple-overview"?e.jsx("section",{className:"page-section-divider",children:e.jsx(Or,{window:G,landscape:Je.data,pinnedFallback:is,canWrite:u,isEmbed:te(),onWindowChange:Y,onPin:O&&u&&!te()?Tt:!Se&&u&&!te()?it:void 0,onUnpin:O||Se||!u||te()?void 0:Jt,onAddCompetitor:O&&u&&!te()?Tt:!Se&&u&&!te()?it:void 0,error:At,onRetry:ft?()=>{Je.refetch()}:void 0,isLoading:ft&&Je.isPending&&Je.data===void 0,scopeLabel:O?`${be?.label??O} market`:Se?"All markets":"Project-wide"})}):null]}):c==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(kg,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(k,ce)=>{await Ft(k,ce)},onRefresh:()=>{n()}}),e.jsx(Pg,{project:s.project,onSave:async k=>{await Ft(s.project.name,k)}}),u&&!te()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),rt==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):rt==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{p.refetch()},children:"Retry"})]}):e.jsx(A,{type:"button",variant:"outline",onClick:()=>{o({to:"/projects/$projectName/portfolio",params:{projectName:d}})},children:Ho(kt.setupAction)})]}):null,e.jsx(Ig,{projectName:s.project.name}),e.jsx(Tg,{projectName:s.project.name}),u&&!te()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),S?e.jsxs(he,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(A,{type:"button",variant:"destructive",disabled:T,onClick:De(oe),children:T?"Deleting...":"Yes, delete project"}),e.jsx(A,{type:"button",variant:"outline",disabled:T,onClick:()=>D(!1),children:"Cancel"})]})]}):e.jsxs(We,{type:"button",variant:"outline",onClick:()=>D(!0),children:[e.jsx(Nu,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):c==="report"?e.jsx(dg,{projectName:s.project.name}):c==="discovery"?e.jsx(rx,{projectName:d}):c==="technical-aeo"?e.jsx(hu,{projectName:s.project.name,projectId:s.project.id,initialRunId:E.siteHealthRunId,onReleaseInitialRun:H}):c==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Wx,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(Dx,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):c==="history"?e.jsx(ux,{projectName:s.project.name}):c==="activity"?e.jsx(Pm,{projectName:s.project.name}):c==="backlinks"?e.jsx(xh,{projectName:s.project.name}):c==="local"?e.jsx(Vm,{projectName:s.project.name,projectId:s.project.id}):c==="search-console"?e.jsx(Eg,{projectName:s.project.name}):null]})}export{Zg as ProjectPage,Lg as patchProjectDashboardCache};
|