@canonry/canonry 4.165.1 → 4.166.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/assets/agent-workspace/skills/canonry/references/server-side-traffic.md +75 -3
- package/assets/assets/{AuditHistoryPanel-IYMElyK5.js → AuditHistoryPanel-CZByTZjH.js} +1 -1
- package/assets/assets/{BacklinksPage-BMqIPRvZ.js → BacklinksPage-DPsSKu1M.js} +1 -1
- package/assets/assets/{HistoryPage-iuETLmwO.js → HistoryPage-9acsanzg.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-BzNAaB8X.js → MeasurementPropertyPage-gIOHHJ4x.js} +1 -1
- package/assets/assets/ProjectPage-CTic0OFR.js +9 -0
- package/assets/assets/{RunRow-BkkYxEjl.js → RunRow-cuE1cBCg.js} +1 -1
- package/assets/assets/{RunsPage-DGTrqrTA.js → RunsPage-Bt6T2Kz2.js} +1 -1
- package/assets/assets/SettingsPage-ChyewFuC.js +1 -0
- package/assets/assets/{SiteHealthSection-k4I71wfJ.js → SiteHealthSection-BYM32RDv.js} +3 -3
- package/assets/assets/{TrafficPage-C8nyb8l1.js → TrafficPage-DMpuFJua.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-ry7Da0pV.js → TrafficSourceDetailPage-D4G26uyv.js} +1 -1
- package/assets/assets/{extract-error-message-BYyBW07F.js → extract-error-message-D7fD7zwP.js} +1 -1
- package/assets/assets/{index-rqOXhYwp.js → index-BliSumN-.js} +20 -20
- package/assets/assets/{react-sigma_core.esm.min-BtG8TWTe.js → react-sigma_core.esm.min-CmW2JaYh.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-BU6C2DKF.js → chunk-GU7T2JUB.js} +24 -2
- package/dist/{chunk-L5SMSDZB.js → chunk-IUWFALUQ.js} +85 -94
- package/dist/{chunk-QKLNTSQ2.js → chunk-KU45I42F.js} +66 -64
- package/dist/{chunk-QDOZEMDK.js → chunk-QFMHIUV7.js} +6 -5
- package/dist/cli.js +29 -28
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-RDGUEEZQ.js → intelligence-service-KRQNQNEB.js} +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +11 -11
- package/assets/assets/ProjectPage-DIzi4Ggo.js +0 -9
- package/assets/assets/SettingsPage-Cwb_Ft9u.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{j as e,r as l,L as _t,n as rs,u as _e,o as Zs,B as zr,C as tl,h as sl,k as nl,D as al}from"./vendor-tanstack-Dock0eH1.js";import{T as ue,t as rl,a as il,u as Qr,C as ll,P as Is,B as A,h as ol,b as cl,c as dl,d as he,i as Y,e as at,f as Ie,I as ze,g as Us,j as ul,k as V,l as ml,m as hl,n as xl,o as pl,p as Hr,q as gl,r as fl,S as hs,s as bl,v as yl,w as us,x as Ot,y as jl,z as Qa,A as Wr,G as ut,D as Na,E as vl,F as Nl,H as wl,J as Sl,K as Ha,L as we,M as Yr,N as Cl,O as Bn,Q as kl,R as Pl,U as Al,V as Rl,W as $l,X as Il,Y as Ll,Z as Tl,_ as Ml,$ as Dl,a0 as El,a1 as ql,a2 as Ol,a3 as Fl,a4 as _l,a5 as Ul,a6 as en,a7 as Gl,a8 as Bl,a9 as Wa,aa as Kl,ab as et,ac as Vl,ad as zl,ae as Ql,af as An,ag as Hl,ah as Wl,ai as Yl,aj as Ls,ak as Xl,al as Jl,am as Zl,an as Xr,ao as ua,ap as eo,aq as Jr,ar as to,as as wa,at as so,au as no,av as ao,aw as Zr,ax as ro,ay as io,az as lo,aA as Ws,aB as xs,aC as oo,aD as co,aE as uo,aF as mo,aG as ei,aH as ho,aI as xo,aJ as po,aK as go,aL as fo,aM as Qe,aN as bo,aO as yo,aP as jo,aQ as vo,aR as No,aS as wo,aT as So,aU as Co,aV as ko,aW as Po,aX as Ao,aY as Ro,aZ as $o,a_ as Io,a$ as Lo,b0 as To,b1 as Mo,b2 as Do,b3 as Eo,b4 as qo,b5 as Oo,b6 as Fo,b7 as _o,b8 as Uo,b9 as Go,ba as Bo,bb as Ko,bc as Vo,bd as zo,be as Qo,bf as Ho,bg as Wo,bh as Yo,bi as Xo,bj as Jo,bk as Zo,bl as ec,bm as tc,bn as Kn,bo as sc,bp as nc,bq as Ya,br as ac,bs as rc,bt as ic,bu as lc,bv as oc,bw as cc,bx as dc,by as uc,bz as mc,bA as hc,bB as xc,bC as pc,bD as gc,bE as ti,bF as fc,bG as bc,bH as yc,bI as jc,bJ as vc,bK as Nc,bL as wc,bM as Xa,bN as Sc,bO as Vn,bP as Cc,bQ as kc,bR as Pc,bS as Ac,bT as Rc,bU as $c,bV as Ic,bW as Lc,bX as si,bY as ni,bZ as Tc,b_ as Mc,b$ as Dc,c0 as Ec,c1 as qc,c2 as pn,c3 as Oc,c4 as Fc,c5 as _c,c6 as Ja,c7 as Uc}from"./index-BliSumN-.js";import{R as Gc}from"./RunRow-cuE1cBCg.js";import{u as Rn,D as Ys,a as Ps,b as Bc,M as Cn,c as Bt,S as Kc}from"./SiteHealthSection-BYM32RDv.js";import{e as Vc,q as $n,U as zc,r as Qc,L as Hc,s as ai,i as Wc,P as In,D as ri,t as Yc,u as Xc,E as Jc,C as Ln,v as Zc}from"./vendor-lucide-nYKv-BB7.js";import{f as Tn,C as bs,a as Ft,b as ps,c as As,d as It,e as mt,g as gs,M as ed,h as ii,i as li,o as as,j as fs,p as td}from"./ChartPrimitives-BoYe2M-i.js";import{u as sd,t as nd,e as ad,a as Za}from"./extract-error-message-D7fD7zwP.js";import{R as tn,C as sn,X as nn,Y as an,T as rn,L as oi,A as Cs,a as ci,b as rd,d as di,e as id}from"./vendor-recharts-D8rt5lKn.js";import{A as ld}from"./AuditHistoryPanel-CZByTZjH.js";import{a as od,b as cd}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function kn(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 dd(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=ud(r,1));return a}function ud(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(),i=String(a.getUTCMonth()+1).padStart(2,"0"),o=String(a.getUTCDate()).padStart(2,"0");return`${r}-${i}-${o}`}function ui(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 md(t,s){const n=ui(t,s);return n===null?null:Math.round(n*100)}function zn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${kn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${kn(t.prior)} ${s})`:`Flat ${n} (${kn(t.prior)} ${s})`}const mi=30;function er(t){return Math.round(t*10)/10}function hd(t){return t.prior>=mi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${er(t.deltaAbs)} vs ${er(t.prior)}`}function xd(t,s,n){return t.prior>=mi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${kn(Math.round(t.deltaAbs))} ${s} ${n}`}const pd=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function hi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function xi(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 pi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(hi).map(xi).filter(Boolean)):new Set}function gi(t,s){const n=hi(t).map(xi).filter(Boolean).filter(a=>!pd.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function gd(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function fd(t,s){const n=pi(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const i of s){if(i.category!=="content"){r.push(i);continue}const o=gi(gd(i),n);!o||a.has(o)||(a.add(o),r.push(i))}return r}function bd(t){const s=pi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const i=gi(r.query,s);return!i||a.has(i)?!1:(a.add(i),!0)})}const fi={queryClass:"all"},yd=["all","non-brand","branded"];function jd(t){return typeof t=="string"&&yd.includes(t)}function vd(t){const s=jd(t.class)?t.class:fi.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 Nd(t,s){return s===null||t===null?!1:t!==s}function wd(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===fi.queryClass?void 0:t.queryClass}}function ma({state:t,label:s}){return e.jsx(ue,{tone:il(t),children:s??rl(t)})}function tr({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"},i=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=new Date(n[i].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=n.map((h,x)=>{const c=new Date(h.createdAt).toLocaleDateString();return`${x===i?"Latest run, ":""}${c}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${u}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:o}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,x)=>{const c=!!(h.model&&x>0&&n[x-1]?.model&&n[x-1].model!==h.model),y=x===i;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${c?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${y?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,c?"model changed":null,y?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[m," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ha(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const i=s.get(r.createdAt);i?i.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:i}])=>({runId:i,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const Sd=320;function Cd(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function sr(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 nr(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 ar(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,i=t[t.length-2].citationState;if(i!=="cited"&&r==="cited")return`Newly ${n}`;if(i==="cited"&&r!=="cited")return"Lost since last run";let o=0;for(let m=t.length-1;m>=0&&t[m].citationState===r;m--)o++;return r==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function kd(t,s){return t.map(n=>bi(n,s))}function bi(t,s){return s==="citations"?t:{...t,citationState:sr(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:sr(n,s)}))}}function rr(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,i=t.length>=2?t[t.length-2].citationState:null,o=r==="cited"||r==="emerging",m=i==="cited"||i==="emerging";return r==="lost"||i!==null&&m&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||i!==null&&!m&&o?{key:s,label:`New ${n}`,tone:"positive"}:i===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Pd(t){const s=ha(kd(t,"mentions")),n=ha(t);return[rr(s,"mentions"),rr(n,"citations")]}function Ad({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 ir({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Pd(t).map(s=>e.jsx(Ad,{signal:s},s.key))})}function Rd({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Qr(),[r,i]=l.useState(new Set),[o,m]=l.useState("mentions"),[u,h]=l.useState(n),x=l.useMemo(()=>{const _=new Map;for(const O of t){const $=O.query,g=s?O.location??null:null,v=s?JSON.stringify([$,g]):$,C=_.get(v)??{key:v,phrase:$,location:g,items:[],rawItems:[]};C.items.push(bi(O,o)),C.rawItems.push(O),_.set(v,C)}return[..._.values()]},[t,o,s]),c=Rn({rows:x,getSearchText:Cd}),y=c.rows.map(_=>_.key),N=y.length>0&&y.every(_=>r.has(_)),f=_=>{i(O=>{const $=new Set(O);return $.has(_)?$.delete(_):$.add(_),$})},b=o==="mentions"?"mentioned":"cited",p=o==="mentions"?"Mention History":"Citation History",T=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{i(_=>{const O=new Set(_);for(const $ of y)N?O.delete($):O.add($);return O})},children:N?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":u==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":u==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),x.length>0?e.jsx(Ys,{value:c.query,onChange:c.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:p}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:c.rows.map(({key:_,phrase:O,location:$,items:g,rawItems:v})=>{const C=r.has(_),J=g.map(M=>M.citationState),z=J.includes("cited")?"cited":J.includes("emerging")?"emerging":J.includes("lost")?"lost":J.every(M=>M==="pending")?"pending":"not-cited",P=ha(g),k=g.filter(M=>M.citationState===ll.cited||M.citationState==="emerging").length,U=ar(P,o);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>f(_),onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),f(_))},tabIndex:0,role:"button","aria-expanded":C,children:[e.jsx("td",{children:e.jsx(Vc,{size:14,className:`transition-transform duration-150 text-muted ${C?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:O}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:$??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:g.map(M=>e.jsx(Is,{provider:M.provider},M.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{state:z,label:nr(z,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${k} of ${g.length} engines ${T}`,children:[k,"/",g.length]})]})}),e.jsx("td",{children:e.jsx(tr,{history:P})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:U}),e.jsx(ir,{items:v})]}),e.jsx("td",{})]}),C&&g.map((M,te)=>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(Is,{provider:M.provider})}),e.jsx("td",{children:e.jsx(ma,{state:M.citationState,label:nr(M.citationState,o)})}),e.jsx("td",{children:e.jsx(tr,{history:M.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ar(M.runHistory,o)}),e.jsx(ir,{items:[v[te]??M]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:je=>{je.stopPropagation(),a(M.id)},children:"View"})})]}),u==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Ld,{item:M,onViewFull:()=>a(M.id)})})]})]},M.id))]},_)})})]})}),c.totalRows===0&&c.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ps,{page:c.page,pageSize:c.pageSize,visibleRows:c.rows.length,totalRows:c.totalRows,onPageChange:c.setPage,itemLabel:c.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",b==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function $d(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...t.competitorDomains.flatMap(r=>{const i=cl(r);return i.length>=4?[i]:[]}),...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 Id(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 Ld({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}=Id(t.answerSnippet,Sd),i=$d(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:ol(a,i)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Td({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const r=s!=null,i=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),i&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const m=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),u=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:u,onClick:r?()=>s(o.domain):void 0,title:r?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(ue,{tone:dl(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),i&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:h=>{h.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function gn({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}const Md=6,Ts="__other__",Rs="_socialTotal";function Dd(t,s=Md){const n=new Map;for(const x of t)n.set(x.source,(n.get(x.source)??0)+x.sessions);const a=[...n.entries()].sort((x,c)=>c[1]!==x[1]?c[1]-x[1]:x[0].localeCompare(c[0])),r=a.slice(0,s),i=new Set(r.map(([x])=>x)),o=Math.max(0,a.length-s),m=new Map;for(const x of t){let c=m.get(x.date);c||(c={date:x.date,[Rs]:0},m.set(x.date,c));const y=i.has(x.source)?x.source:Ts;c[y]=(c[y]??0)+x.sessions,c[Rs]=(c[Rs]??0)+x.sessions}const u=[...m.values()].sort((x,c)=>String(x.date).localeCompare(String(c.date))),h=r.map(([x])=>x);return o>0&&h.push(Ts),{data:u,sources:h,otherCount:o}}function $s(t){return t.replace(/\+/g," ")}function yi(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const lr="_totalSessions",or="_organicSessions";function Ed(t,s){const n=new Map;for(const o of s)n.set(o.date,{[lr]:o.sessions,[or]:o.organicSessions});for(const o of t.days){let m=n.get(o.date);m||(m={[lr]:0,[or]:0},n.set(o.date,m));for(const u of o.bySource)m[u.source]=(m[u.source]??0)+u.sessions}const a=[...n.entries()].sort(([o],[m])=>o.localeCompare(m)).map(([o,m])=>({date:o,...m})),r=a.map(o=>o.date),i=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:i}}const qd=["7d","30d","90d","all"],ts=mt,xa=It.textDim,ji=It.textFaint,Gs=25;function Od(t){return Bc(t.landingPage)}const Fd=25,Qn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function fn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function vi(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 _d({projectName:t}){const{data:s,isLoading:n,isError:a}=sd(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."," ",!Y()&&e.jsx(_t,{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."," ",!Y()&&e.jsxs(e.Fragment,{children:[e.jsx(_t,{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(i=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:i.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ue,{tone:nd(i.status),children:i.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:i.lastSyncedAt?vi(i.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Y()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(_t,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:i.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},i.id))})]})})]})}function Ud({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(_d,{projectName:t}),e.jsx(Gd,{projectName:t})]})}function Gd({projectName:t}){const s=rs(),[n,a]=l.useState(null),[r,i]=l.useState(null),[o,m]=l.useState(!0),[u,h]=l.useState(!1),[x,c]=l.useState(!1),[y,N]=l.useState(null),[f,b]=l.useState(null),[p,T]=l.useState("sessions"),[_,O]=l.useState("desc"),[$,g]=l.useState("sessions"),[v,C]=l.useState("desc"),[J,z]=l.useState("sessions"),[P,k]=l.useState("desc"),[U,M]=l.useState("sessions"),[te,je]=l.useState("desc"),[le,Q]=l.useState(Qn),[de,oe]=l.useState([]),[G,F]=l.useState([]),[w,Z]=l.useState(!1),[re,ce]=l.useState("30d");async function K(E){m(!0),N(null);try{const Ne=await s.fetchQuery({...ul({client:V,path:{name:t}}),staleTime:Us});if(E.current)return;if(a(Ne),!Ne.connected){i(null),Q(Qn),oe([]),F([]),m(!1);return}const me=re==="all"?void 0:re,[fe,kt,Mt,tt]=await Promise.all([s.fetchQuery({...ml({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).then(Pt=>Pt),s.fetchQuery({...hl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>Qn),s.fetchQuery({...xl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>[]),s.fetchQuery({...pl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>[])]);if(E.current)return;i(fe),Q(kt),oe(Mt),F(tt),m(!1)}catch(Ne){if(E.current)return;N(Ne instanceof Error?Ne.message:"Failed to load GA4 data"),m(!1)}}l.useEffect(()=>{const E={current:!1};return K(E),()=>{E.current=!0}},[t,re,s]);async function xe(){h(!0),N(null),b(null);try{const E=await Hr(t);b(`Synced ${E.rowCount.toLocaleString()} page rows, ${E.aiReferralCount.toLocaleString()} AI and ${E.socialReferralCount.toLocaleString()} social referral rows (${E.days} days)`),await at(s,"ga"),await K({current:!1})}catch(E){N(E instanceof Error?E.message:"Sync failed")}finally{h(!1)}}async function q(){c(!0),N(null),b(null);try{await gl(t),await at(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),i(null),b("GA4 disconnected")}catch(E){N(E instanceof Error?E.message:"Disconnect failed")}finally{c(!1)}}function ie(E){p===E?O(Ne=>Ne==="desc"?"asc":"desc"):(T(E),O("desc"))}function Se(E){$===E?C(Ne=>Ne==="desc"?"asc":"desc"):(g(E),C("desc"))}function Xe(E){J===E?k(Ne=>Ne==="desc"?"asc":"desc"):(z(E),k("desc"))}const rt=l.useMemo(()=>r?.topPages?[...r.topPages].sort((E,Ne)=>{const me=E[p],fe=Ne[p];return typeof me=="string"&&typeof fe=="string"?_==="asc"?me.localeCompare(fe):fe.localeCompare(me):_==="asc"?me-fe:fe-me}):[],[r?.topPages,p,_]),it=l.useMemo(()=>r?.aiReferrals?[...r.aiReferrals].sort((E,Ne)=>{const me=E[$],fe=Ne[$];return typeof me=="string"&&typeof fe=="string"?v==="asc"?me.localeCompare(fe):fe.localeCompare(me):v==="asc"?me-fe:fe-me}):[],[r?.aiReferrals,$,v]),Ge=l.useMemo(()=>r?.aiReferralLandingPages?[...r.aiReferralLandingPages].sort((E,Ne)=>{const me=E[U],fe=Ne[U];return typeof me=="string"&&typeof fe=="string"?te==="asc"?me.localeCompare(fe):fe.localeCompare(me):te==="asc"?me-fe:fe-me}):[],[r?.aiReferralLandingPages,U,te]),X=Rn({rows:Ge,getSearchText:Od,pageSize:Fd}),Be=X.totalRows>0?`${X.totalRows.toLocaleString()} ${X.hasQuery?X.totalRows===1?"match":"matches":X.totalRows===1?"row":"rows"}`:X.hasQuery&&(r?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ve(E){X.setPage(1),U===E?je(Ne=>Ne==="desc"?"asc":"desc"):(M(E),je("desc"))}const Pe=l.useMemo(()=>r?.socialReferrals?[...r.socialReferrals].sort((E,Ne)=>{const me=E[J],fe=Ne[J];return typeof me=="string"&&typeof fe=="string"?P==="asc"?me.localeCompare(fe):fe.localeCompare(me):P==="asc"?me-fe:fe-me}):[],[r?.socialReferrals,J,P]),{socialChartData:He,socialChartSources:Ce,socialOtherCount:ve}=l.useMemo(()=>{const E=Dd(G);return{socialChartData:E.data,socialChartSources:E.sources,socialOtherCount:E.otherCount}},[G]),{chartData:D,chartSources:R,dateRange:I}=l.useMemo(()=>{const E=Ed(le,de);return{chartData:E.data,chartSources:E.sources,dateRange:E.dateRange}},[le,de]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Y()?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(Bd,{projectName:t,onConnected:()=>{(async()=>(await at(s,"ga"),await K({current:!1})))()}});const be=r?.organicSharePctDisplay??"0%",De=r?.channelBreakdown?.organic.sharePctDisplay??be,H=r?.channelBreakdown?.organic.sessions??r?.totalOrganicSessions??0,Ee=r?.aiSessionsDeduped??0,lt=r?.channelBreakdown?.ai.sessions??r?.aiSessionsBySession??0,bt=r?.channelBreakdown?.ai.sharePctDisplay??r?.aiSharePctBySessionDisplay??"0%",ke=r?.paidAiSessionsBySession??0,Oe=r?.paidAiSharePctBySessionDisplay??"0%",ht=r?new Set(r.aiReferrals.map(E=>E.source.toLowerCase())).size:0,Ue=it[0]??null,We=r?.totalDirectSessions??0,Ae=r?.directSharePctDisplay??"0%",jt=r?.channelBreakdown?.direct.sessions??We,Ct=r?.channelBreakdown?.direct.sharePctDisplay??Ae,Le=r?.channelBreakdown?.other.sessions??r?.otherSessions??0,Te=r?.channelBreakdown?.other.sharePctDisplay??r?.otherSharePctDisplay??"0%",ot=r?.socialSessions??0,Fe=r?.socialSharePctDisplay??"0%",Tt=r?.channelBreakdown?.social.sessions??ot,vt=r?.channelBreakdown?.social.sharePctDisplay??Fe,pt=r?new Set(r.socialReferrals.map(E=>E.source.toLowerCase())).size:0,Je=Pe[0]??null;return e.jsxs(e.Fragment,{children:[y&&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:y}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:f}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!Y()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ie(xe),children:[e.jsx($n,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ie(q),children:[e.jsx(zc,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(ze,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${r?.periodStart&&r?.periodEnd?` Data available: ${new Date(r.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(r.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:qd.map(E=>e.jsx("button",{type:"button","aria-pressed":re===E,className:`segmented-option ${re===E?"segmented-option-active":""}`,onClick:()=>ce(E),children:E==="all"?"All":E},E))})]}),r?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Hn,{value:fn(r.totalSessions),label:"Total Sessions",subtitle:r.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Hn,{value:fn(r.totalOrganicSessions),label:"Organic Sessions",subtitle:`${be} of total`,tone:"positive"}),e.jsx(Hn,{value:fn(r.totalUsers),label:"Total Users",subtitle:r.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."}),!Y()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ie(xe),children:[e.jsx($n,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),r&&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."})]})]}),I&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(I.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(I.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),D.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:R.length>0?"AI vs. total sessions":"All sessions (baseline)"}),R.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),R.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(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:D,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(E,Ne)=>{const me=typeof E=="number"?E.toLocaleString():String(E??0),fe=String(Ne??"");return fe==="_totalSessions"?[me,"Total Sessions"]:fe==="_organicSessions"?[me,"Organic Sessions"]:[me,fe]}}),e.jsx(oi,{wrapperStyle:{fontSize:11,color:It.text},formatter:E=>E==="_totalSessions"?"Total Sessions":E==="_organicSessions"?"Organic Sessions":E}),e.jsx(Cs,{type:"monotone",dataKey:"_totalSessions",stroke:It.textFaint,fill:It.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),R.map((E,Ne)=>e.jsx(Cs,{type:"monotone",dataKey:E,stackId:"ai",stroke:ts[Ne%ts.length],fill:ts[Ne%ts.length],fillOpacity:.4,strokeWidth:1.5},E))]})})})]}),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:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Lt,{label:"Organic",value:De,hint:`${H.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(Lt,{label:"Social",value:vt,hint:`${Tt.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(Lt,{label:"Direct",value:Ct,hint:`${jt.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(Lt,{label:"Known AI referrers (lower bound)",value:bt,hint:ke>0?`${lt.toLocaleString()} sessions · ${ke.toLocaleString()} paid`:`${lt.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(Lt,{label:"Other channels",value:Te,hint:`${Le.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),Ue&&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:Ue.source})," via ",Ue.medium,", accounting for ",Ue.sessions.toLocaleString()," sessions.",ke>0&&e.jsxs("span",{children:[" Paid AI: ",ke.toLocaleString()," sessions (",Oe,")."]})]})]}),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:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.aiReferrals.length>0?`${ht} unique sources, ${r.aiReferrals.length} rows`:"No source rows"})]}),r.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(St,{label:"Source",sortKey:"source",current:$,dir:v,onSort:Se,align:"left"}),e.jsx(St,{label:"Medium",sortKey:"medium",current:$,dir:v,onSort:Se,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(St,{label:"Sessions",sortKey:"sessions",current:$,dir:v,onSort:Se,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:it.map(E=>e.jsx(Vd,{referral:E,totalSessions:Ee},`${E.source}:${E.medium}:${E.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:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-muted",children:Be})]}),r.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ys,{value:X.query,onChange:X.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),X.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(St,{label:"Landing Page",sortKey:"landingPage",current:U,dir:te,onSort:Ve,align:"left"}),e.jsx(St,{label:"Source",sortKey:"source",current:U,dir:te,onSort:Ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:U,dir:te,onSort:Ve,align:"right"})]})}),e.jsx("tbody",{children:X.rows.map(E=>e.jsx(zd,{row:E},`${E.landingPage}:${E.source}:${E.medium}:${E.sourceDimension}`))})]})}),e.jsx(Ps,{page:X.page,pageSize:X.pageSize,visibleRows:X.rows.length,totalRows:X.totalRows,onPageChange:X.setPage,itemLabel:X.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:()=>X.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 landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),r&&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."})]})]}),He.length>0&&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:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions over time"})]}),ve>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ce.length-1," sources · ",ve," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:He,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(E,Ne)=>{const me=typeof E=="number"?E.toLocaleString():String(E??0),fe=String(Ne??"");if(fe===Rs)return[me,"Total Social"];if(fe===Ts){const kt=`Other (${ve} source${ve===1?"":"s"})`;return[me,kt]}return[me,$s(fe)]}}),e.jsx(Cs,{type:"monotone",dataKey:Rs,stroke:ji,fill:It.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ce.map((E,Ne)=>{const fe=E===Ts?xa:ts[Ne%ts.length];return e.jsx(Cs,{type:"monotone",dataKey:E,stackId:"social",stroke:fe,fill:fe,fillOpacity:.4,strokeWidth:1.5},E)})]})})}),e.jsx(Hd,{sources:Ce,otherCount:ve})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",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:"Social media visits"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Lt,{label:"Social Sessions",value:fn(ot),hint:`${ot.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Lt,{label:"Share of Traffic",value:Fe,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Lt,{label:"Platforms",value:String(pt),hint:`${r.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Je&&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:`${Je.source} via ${Je.medium}`,children:yi($s(Je.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Je.medium,children:["via ",$s(Je.medium)," · ",Je.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(Lt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Lt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Lt,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),e.jsxs(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:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.socialReferrals.length>0?Pe.length>Gs&&!w?`Top ${Gs} of ${Pe.length}`:`${Pe.length} rows`:"No source rows"})]}),r.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(St,{label:"Source",sortKey:"source",current:J,dir:P,onSort:Xe,align:"left"}),e.jsx(St,{label:"Medium",sortKey:"medium",current:J,dir:P,onSort:Xe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:J,dir:P,onSort:Xe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(St,{label:"Users",sortKey:"users",current:J,dir:P,onSort:Xe,align:"right"})]})}),e.jsx("tbody",{children:(w?Pe:Pe.slice(0,Gs)).map(E=>e.jsx(Qd,{referral:E,totalSessions:ot},`${E.source}:${E.medium}:${E.channelGroup}`))})]})}),Pe.length>Gs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>Z(E=>!E),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:w?`Show top ${Gs}`:`Show all ${Pe.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."})]})]})]})]})]}),r&&r.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("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(St,{label:"Landing Page",sortKey:"landingPage",current:p,dir:_,onSort:ie,align:"left"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:p,dir:_,onSort:ie,align:"right"}),e.jsx(St,{label:"Organic",sortKey:"organicSessions",current:p,dir:_,onSort:ie,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:rt.map(E=>e.jsx(Kd,{page:E},E.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:r?.lastSyncedAt?`Last synced ${vi(r.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:r?`${r.topPages.length} pages · ${r.aiReferrals.length} AI rows · ${r.socialReferrals.length} social rows`:""})]})]})}function Bd({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,i]=l.useState(null),[o,m]=l.useState(null),[u,h]=l.useState(!1),[x,c]=l.useState(null),y=l.useRef(null),N=l.useCallback(b=>{const p=b.target.files?.[0];if(!p)return;c(null),i(p.name);const T=new FileReader;T.onload=()=>{const _=T.result;try{const O=JSON.parse(_);if(!O.client_email||!O.private_key){c("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),m(null);return}m(_)}catch{c("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},T.onerror=()=>{c("Failed to read file."),m(null)},T.readAsText(p)},[]);async function f(){if(c(null),!n.trim()){c("Property ID is required.");return}if(!o){c("Please upload a service account key file.");return}h(!0);try{await fl(t,{propertyId:n.trim(),keyJson:o});try{await Hr(t)}catch{}s()}catch(b){c(b instanceof Error?b.message:"Failed to connect GA4")}finally{h(!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."}),x&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:x}),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:b=>a(b.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:y,type:"file",accept:".json,application/json",onChange:N,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>y.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(Qc,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(A,{variant:"default",size:"sm",disabled:u||!n.trim()||!o,onClick:Ie(f),children:u?"Connecting & syncing…":"Connect GA4"})]})}function St({label:t,sortKey:s,current:n,dir:a,onSort:r,align:i}){const o=n===s;return e.jsx("th",{className:`py-1 ${i==="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}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Ni={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Hn({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 ${Ni[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Lt({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 ${Ni[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Kd({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 wi={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Si={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 Vd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=wi[t.sourceDimension]??t.sourceDimension,r=Si[t.sourceDimension]??"",i=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:i})}),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 zd({row:t}){const s=wi[t.sourceDimension]??t.sourceDimension,n=Si[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(Cn,{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 Qd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=$s(t.source),i=$s(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:i}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Hd({sources:t,otherCount:s}){const n=[{key:Rs,color:ji,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Ts)n.push({key:Ts,color:xa,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const i=$s(r);n.push({key:r,color:ts[a%ts.length]??xa,label:yi(i,32),tooltip:i})}}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 Wd(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 Yd=["7d","30d","90d","all"],bn=500,cr=[{key:"clicks",label:"Clicks",color:mt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:mt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:gs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:mt[2],inverted:!0,format:t=>t.toFixed(1)}],Zt=25,Xd="canonry:google-oauth-complete",Jd=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Zd(t,s,n){const{startIndex:a,endIndex:r}=t,i=a!==void 0&&r!==void 0&&Number.isInteger(a)&&Number.isInteger(r)&&a>=0&&r>=a?r-a+1:n;if(!Number.isFinite(t.start)||!Number.isFinite(t.end)||t.start<=0||t.end<0)return"— no percentage baseline";if(t.slope===0)return`→ 0% over ${i}d`;const o=ui(t.end,t.start);if(o===null)return"— no percentage baseline";const m=Math.abs(o*100),u=m<.1?"<0.1%":`${Jd.format(m)}%`;return`${(s?t.slope<0:t.slope>0)?"↑":"↓"} ${u} over ${i}d`}function dr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function ur(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 mr(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function eu({projectName:t,refreshNonce:s}){const n=rs(),[a,r]=l.useState(!1),[i,o]=l.useState([]),[m,u]=l.useState([]),[h,x]=l.useState([]),[c,y]=l.useState(null),[N,f]=l.useState([]),[b,p]=l.useState([]),[T,_]=l.useState(null),[O,$]=l.useState(""),[g,v]=l.useState(""),[C,J]=l.useState("30"),[z,P]=l.useState(!1),[k,U]=l.useState("30d"),[M,te]=l.useState(["clicks","impressions"]),[je,le]=l.useState(!0),[Q,de]=l.useState(null),[oe,G]=l.useState(0),[F,w]=l.useState({startDate:"",endDate:"",query:"",page:""}),[Z,re]=l.useState(0),[ce,K]=l.useState(!1),[xe,q]=l.useState(0),[ie,Se]=l.useState(!1),[Xe,rt]=l.useState(""),[it,Ge]=l.useState(!0),[X,Be]=l.useState(!1),[Ve,Pe]=l.useState(!1),[He,Ce]=l.useState(!1),[ve,D]=l.useState(!1),[R,I]=l.useState(!1),[be,De]=l.useState(!1),[H,Ee]=l.useState(null),[lt,bt]=l.useState(!1),[ke,Oe]=l.useState(!1),[ht,Ue]=l.useState(null),[We,Ae]=l.useState(null),[jt,Ct]=l.useState([]),[Le,Te]=l.useState(new Set),[ot,Fe]=l.useState({}),[Tt,vt]=l.useState(new Set),[pt,Je]=l.useState(""),[E,Ne]=l.useState(null),[me,fe]=l.useState(""),[kt,Mt]=l.useState(!1),[tt,Pt]=l.useState(!1),[is,Ds]=l.useState(!1),[Dt,Es]=l.useState(!1),[Ze,qs]=l.useState("indexed"),[Nt,Os]=l.useState(null),Qt=!!(F.query.trim()||F.page.trim()||Nt),ys=Nt!==null,ls=l.useMemo(()=>{if(!Nt)return h;const{key:d,dir:L}=Nt;return[...h].sort((W,ae)=>{const $e=d===hs.CTR?Number.isFinite(W.ctr)?W.ctr:0:W[d],qe=d===hs.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[d];return L==="asc"?$e-qe:qe-$e})},[h,Nt]),Ye=Rn({rows:ls,pageSize:Bt}),js=ie?Ye.rows:ls,Et=Rn({rows:(ht??[]).filter(d=>d.path.toLowerCase().includes(pt.trim().toLowerCase())),pageSize:Bt}),[yt,vs]=l.useState([]),[st,Ht]=l.useState(null),[j,ge]=l.useState(1),ye=l.useMemo(()=>{if(yt.length<2)return null;const d=yt[yt.length-1],L=yt[yt.length-2];return{indexed:d.indexed-L.indexed,notIndexed:d.notIndexed-L.notIndexed}},[yt]);l.useEffect(()=>{ge(1)},[H,Ze,st]);const S=l.useMemo(()=>st?(H?.reasonGroups??[]).find(d=>d.reason===st):void 0,[H,st]),B=l.useMemo(()=>H?Ze==="indexed"?H.indexed:Ze==="deindexed"?H.deindexed:Ze==="notIndexed"?st?S?.urls??[]:(H.reasonGroups??[]).length===0?H.notIndexed:[]:[]:[],[H,Ze,st,S]),pe=Math.max(1,Math.ceil(B.length/Zt)),ee=Math.min(Math.max(1,j),pe),se=(ee-1)*Zt,Re=l.useMemo(()=>H?.indexed.slice(se,se+Zt)??[],[H,se]),Wt=l.useMemo(()=>H?.notIndexed.slice(se,se+Zt)??[],[H,se]),xt=l.useMemo(()=>H?.deindexed.slice(se,se+Zt)??[],[H,se]),Fs=l.useMemo(()=>(S?.urls??[]).slice(se,se+Zt),[S,se]),[At,Yt]=l.useState(!1),[Ma,Me]=l.useState(null),[Ut,un]=l.useState(null),[Da,Gt]=l.useState(null);function Vi(d,L){const W=ad(d),ae=Wd(W);ae?(un(ae),Me(null)):(un(null),Me(W.message||L))}const wt=i.find(d=>d.connectionType==="gsc"),os=(wt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),qn=jt.length>0?jt:(ht??[]).map(d=>d.path),Ea=qn.filter(d=>ht?.some(L=>L.path===d&&L.isSitemapsIndex)).length,zi=Ea===1?"Resubmit sitemap index":Ea>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Qi=h.length>0||N.length>0||b.length>0,On=bl(),Fn=yl();async function qa(d,L=!1){if(!d){u([]),$("");return}Pe(!0);try{const{sites:W}=await n.fetchQuery({...Ll({client:V,path:{name:t}}),staleTime:L?0:ut});u(W),$(d.propertyId??W[0]?.siteUrl??""),un(null)}catch(W){u([]),Vi(W,"Failed to load Search Console properties")}finally{Pe(!1)}}async function _s(d){D(!0);const L=d??Z;try{const W=Qt?bn:Bt,ae=Qt?0:L,$e={limit:String(W)};F.startDate&&($e.startDate=F.startDate),F.endDate&&($e.endDate=F.endDate),F.query&&($e.query=F.query),F.page&&($e.page=F.page),ae>0&&($e.offset=String(ae)),k&&k!=="all"&&!F.startDate&&($e.window=k);const qe=await n.fetchQuery({...Nl({client:V,path:{name:t},query:$e}),staleTime:ut}),Ke=qe.rows;Qt?(K(!1),x(Ke),q(Ke.length),Se(!0)):(K(ae+Ke.length<qe.totalMatching),x(Ke),q(0),Se(!1))}catch(W){x([]),K(!1),q(0),Me(W instanceof Error?W.message:"Failed to load GSC performance data")}finally{D(!1)}}async function _n(){try{const d={};F.startDate&&(d.startDate=F.startDate),F.endDate&&(d.endDate=F.endDate),k&&k!=="all"&&!F.startDate&&(d.window=k);const L=await n.fetchQuery({...vl({client:V,path:{name:t},query:d}),staleTime:ut});y(L)}catch{y(null)}}async function mn(d=!1){I(!0);try{const L=Xe.trim()||void 0,W={limit:"20"};L&&(W.url=L);const[ae,$e]=await Promise.all([n.fetchQuery({...$l({client:V,path:{name:t},query:W}),staleTime:d?0:ut}),n.fetchQuery({...Il({client:V,path:{name:t}}),staleTime:d?0:ut})]);f(ae),p($e)}catch(L){f([]),p([]),Me(L instanceof Error?L.message:"Failed to load GSC inspection history")}finally{I(!1)}}async function Oa(d=!1){bt(!0);try{const[L,W]=await Promise.all([n.fetchQuery({...Yr({client:V,path:{name:t}}),staleTime:d?0:ut}),n.fetchQuery({...Cl({client:V,path:{name:t}}),staleTime:d?0:ut}).catch(()=>[])]);Ee(L),vs(W)}catch(L){Ee(null),vs([]),Me(L instanceof Error?L.message:"Failed to load coverage data")}finally{bt(!1)}}async function Fa(d){Yt(!0),Me(null);try{const L=await Ha(t,{urls:d}),{succeeded:W,failed:ae,total:$e}=L.summary;we({title:"Indexing requested",detail:ae===0?`${W} URL${W!==1?"s":""} submitted for indexing.`:`${W}/${$e} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(L){Me(L instanceof Error?L.message:"Failed to request indexing")}finally{Yt(!1)}}async function Hi(){Yt(!0),Me(null);try{const d=await Ha(t,{urls:[],allUnindexed:!0}),{succeeded:L,failed:W,total:ae}=d.summary;we({title:"Indexing requested",detail:W===0?`${L} unindexed URL${L!==1?"s":""} submitted for indexing.`:`${L}/${ae} submitted successfully, ${W} failed.`,tone:W===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(d){Me(d instanceof Error?d.message:"Failed to request indexing")}finally{Yt(!1)}}async function Un(){Oe(!0),Me(null);try{const d=await Bn(t);n.setQueryData(kl({client:V,path:{name:t}}),d),Ue(d.sitemaps),Ae(d.summary),Ct(d.preferredSubmissionUrls),Te(new Set),Fe({}),d.sitemaps.length===0&&Gt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(d){Me(d instanceof Error?d.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function Wi(d){const L=Le.has(d);if(Te(W=>{const ae=new Set(W);return L?ae.delete(d):ae.add(d),ae}),!(L||ot[d])){vt(W=>new Set(W).add(d));try{const W=await Bn(t,d);Fe(ae=>({...ae,[d]:W.sitemaps}))}catch(W){Me(W instanceof Error?W.message:"Failed to load sitemap files")}finally{vt(W=>{const ae=new Set(W);return ae.delete(d),ae})}}}async function Ns(d){if(!os||d.length===0)return;const L=[...new Set(d)];Pt(!0),Me(null),Ne({completed:0,total:L.length});let W=0,ae=0,$e=0,qe=null;try{for(let ct=0;ct<L.length;ct+=50){const ne=L.slice(ct,ct+50);try{const dt=await Pl(t,ne);W+=dt.summary.accepted,ae+=dt.summary.failed,$e+=ne.length,Ne({completed:$e,total:L.length})}catch(dt){$e+=ne.length;const Xt=ne.length,hn=L.length-$e,xn=dt instanceof Error?dt.message:"The batch request failed",Jt=`${W} accepted, ${ae} failed, ${Xt} unconfirmed, ${hn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;qe=`Sitemap submission stopped after a batch request failed. ${Jt} ${xn}`,Me(qe),we({title:"Sitemap resubmission partially completed",detail:Jt,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const Ke=L.length;we({title:ae===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ae===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${W}/${Ke} sitemap submissions; ${ae} failed. Indexing is not guaranteed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),fe("")}catch(Ke){Me(Ke instanceof Error?Ke.message:"Failed to submit sitemap to Google")}finally{Pt(!1),Ne(null),await Un(),qe&&Me(qe)}}async function Yi(){Pt(!0);const d=ht??[];try{const L=d.filter(ae=>ae.isSitemapsIndex),W=[];for(let ae=0;ae<L.length;ae+=4)(await Promise.all(L.slice(ae,ae+4).map(async qe=>{const Ke=ot[qe.path];if(Ke)return Ke;const ct=await Bn(t,qe.path);return Fe(ne=>({...ne,[qe.path]:ct.sitemaps})),ct.sitemaps}))).forEach((qe,Ke)=>{W.push(...qe.length>0?qe.map(ct=>ct.path):[L[ae+Ke].path])});await Ns([...d.filter(ae=>!ae.isSitemapsIndex).map(ae=>ae.path),...W])}catch(L){Me(L instanceof Error?L.message:"Failed to load sitemap files"),Pt(!1)}}async function _a(d){Mt(!0),Me(null);try{await Al(t,"gsc",d),await at(n,"google"),o(L=>L.map(W=>W.connectionType==="gsc"?{...W,sitemapUrl:d}:W)),we({title:"Default sitemap updated",detail:d,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(L){Me(L instanceof Error?L.message:"Failed to set the default sitemap")}finally{Mt(!1)}}async function Ua(d){try{await Fn.mutateAsync({projectName:t,projectLabel:t,opts:d?{sitemapUrl:d}:void 0})}catch{}}async function Ga(){Ge(!0),Me(null);try{const[d,L]=await Promise.all([Wr().catch(()=>null),n.fetchQuery({...Na({client:V,path:{name:t}}),staleTime:ut}).catch(()=>[])]);r(!!d?.google?.configured),o(L);const W=L.find(ae=>ae.connectionType==="gsc");await Promise.all([qa(W),_s(),_n(),mn(),Oa(),W?.propertyId?Un():Promise.resolve()])}finally{Ge(!1)}}l.useEffect(()=>{Ga()},[t,s]),l.useEffect(()=>{re(0),de(null),w(d=>d.startDate||d.endDate?{...d,startDate:"",endDate:""}:d),G(d=>d+1),_n()},[k]);const Ba=l.useRef(!1);l.useEffect(()=>{if(!Ba.current){Ba.current=!0;return}re(0),Ye.setPage(1),_s(0)},[oe]);function Gn(d){const L=Q===d?null:d;de(L),w(W=>({...W,startDate:L??"",endDate:L??""})),G(W=>W+1)}const Ka=l.useRef(!1);l.useEffect(()=>{if(!Ka.current){Ka.current=!0;return}re(0),_s(0)},[ys]);async function Va(){if(!a){Me("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Be(!0),Me(null),Gt(null);try{let d=function(dt){if(dt.source!==ae||dt.origin!==$e||!dt.data||typeof dt.data!="object")return;const Xt=dt.data;Xt.type!==Xd||Xt.connectionType!=="gsc"||ne(!0)};const{authUrl:L,redirectUri:W}=await Sl(t,"gsc");if(!L.startsWith("https://accounts.google.com/")){Me("Unexpected OAuth redirect URL. Please try again.");return}const ae=window.open(L,"_blank","width=600,height=700");if(!ae){window.location.assign(L);return}const $e=W?new URL(W).origin:window.location.origin;let qe=!1,Ke=null;const ct=()=>{Ke!==null&&window.clearInterval(Ke),window.removeEventListener("message",d)},ne=async dt=>{if(!qe){qe=!0,ct(),Gt(dt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await at(n,"google"),await Ga()}finally{Gt(null)}}};window.addEventListener("message",d),Gt("Finish the Google consent flow in the popup. This page will refresh automatically."),Ke=window.setInterval(()=>{ae.closed&&ne(!1)},1e3)}catch(d){Me(d instanceof Error?d.message:"Failed to start OAuth flow")}finally{Be(!1)}}async function Xi(){Me(null),Gt(null);try{await wl(t,"gsc"),await at(n,"google"),o(d=>d.filter(L=>L.connectionType!=="gsc")),u([]),$("")}catch(d){Me(d instanceof Error?d.message:"Failed to disconnect")}}async function Ji(){if(O){Ce(!0),Me(null);try{await Tl(t,"gsc",O),await at(n,"google"),o(d=>d.map(L=>L.connectionType==="gsc"?{...L,propertyId:O}:L)),we({title:"GSC property updated",detail:`${t} is now linked to ${O}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(d){Me(d instanceof Error?d.message:"Failed to save GSC property")}finally{Ce(!1)}}}async function Zi(){Me(null),Gt(null);try{await On.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(C,10)||void 0,full:z||void 0}}),await at(n,"gsc")}catch{}}async function za(){if(g.trim()){De(!0),Me(null),Gt(null);try{const d=await Rl(t,g.trim());await at(n,"gsc"),_(d),v(""),await mn()}catch(d){Me(d instanceof Error?d.message:"Failed to inspect URL")}finally{De(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),Ut&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:Ut.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Ut.message}),(us(Ut.enableUrl)||us(Ut.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[us(Ut.enableUrl)&&e.jsx("a",{href:us(Ut.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),us(Ut.indexingApiUrl)&&e.jsx("a",{href:us(Ut.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>un(null),children:"×"})]})}),Ma&&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:[Ma,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Me(null),children:"×"})]}),Da&&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:[Da,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Gt(null),children:"×"})]}),it?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[wt?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:wt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",H?.lastInspectedAt?Ot(H.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ie(Xi),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(ue,{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:X,onClick:Ie(Va),children:X?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(_t,{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."})]})]})]}),(wt||Qi)&&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:`Tile percentages show the fitted trend's relative change from its first measured day to its last. 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 ${Bt} per page.`})]}),c?.window?.startDate&&c.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[c.window.startDate," to ",c.window.endDate,(c.window.daysSinceLatestData??0)>0&&` · latest data ${c.window.daysSinceLatestData} day${c.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:Yd.map(d=>e.jsx("button",{type:"button","aria-pressed":k===d,className:`segmented-option ${k===d?"segmented-option-active":""}`,onClick:()=>{U(d),re(0),Ye.setPage(1)},children:d==="all"?"All":d},d))}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ve,onClick:()=>{re(0),Ye.setPage(1),_s(0),_n()},children:ve?"Loading…":"Apply filters"})]})]}),c&&c.daily.length>0&&(()=>{const{totals:d,daily:L,trends:W}=c,$e=cr.filter(ne=>M.includes(ne.key)).map(ne=>({dataKey:ne.key,label:ne.label,color:ne.color,axisId:ne.key,inverted:ne.inverted,formatValue:ne.format,trend:je?W?.[ne.key]??null:null})),qe=ne=>d[ne]??null,Ke=new Map(L.map(ne=>[ne.date,ne])),ct=L.length===0?[]:dd(L[0].date,L[L.length-1].date).map(ne=>Ke.get(ne)??{date:ne});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:cr.map(ne=>{const dt=M.includes(ne.key),Xt=qe(ne.key),hn=W?.[ne.key]??null,xn=Xt===null;return e.jsxs("button",{type:"button","aria-pressed":dt,disabled:xn,className:`rounded-md border px-3 py-2 text-left transition-colors ${dt?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${xn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(Jt=>Jt.includes(ne.key)?Jt.length===1?Jt:Jt.filter(el=>el!==ne.key):[...Jt,ne.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:dt?ne.color:"transparent",border:`1px solid ${ne.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ne.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Xt===null?"—":ne.format(Xt)}),hn&&e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Zd(hn,ne.inverted,d.days)})]},ne.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:je,onChange:ne=>le(ne.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(ed,{data:ct,xKey:"date",series:$e,xTickFormatter:Tn,labelFormatter:ps,onSelectX:Gn,selectedX:Q})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:L.map(ne=>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":Q===ne.date,onClick:()=>Gn(ne.date),children:[ps(ne.date),": ",ne.clicks," clicks, ",ne.impressions," impressions"]},ne.date))}),Q&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",ps(Q)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Gn(Q),children:["Show all ",d.days," days"]})]}),d.position!==null&&(d.positionDays??d.days)<d.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",d.positionDays," of ",d.days," days. The rest have no property-level position recorded."]}),(d.position===null||d.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:F.startDate,onChange:d=>w(L=>({...L,startDate:d.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:F.endDate,onChange:d=>w(L=>({...L,endDate:d.target.value}))}),e.jsx(Ys,{value:F.query,onChange:d=>w(L=>({...L,query:d})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Ys,{value:F.page,onChange:d=>w(L=>({...L,page:d})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(hs).map(d=>e.jsx("th",{className:"text-right","aria-sort":Nt?.key===d?Nt.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:()=>{Ye.setPage(1),Os(L=>L?.key===d?L.dir==="desc"?{key:d,dir:"asc"}:null:{key:d,dir:"desc"})},children:[jl[d],Nt?.key===d?Nt.dir==="desc"?" ↓":" ↑":""]})},d))]})}),e.jsx("tbody",{children:js.map((d,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:d.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Cn,{value:d.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(d.ctr)?d.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.position.toFixed(1)})]},`${d.date}:${d.query}:${d.page}:${L}`))})]})}),e.jsx(Ps,{page:ie?Ye.page:Math.floor(Z/Bt)+1,pageSize:Bt,visibleRows:js.length,totalRows:ie?xe:void 0,hasNextPage:ie?void 0:ce,disabled:ve,itemLabel:ie?"matches":"rows",onPageChange:d=>{if(ie){Ye.setPage(d);return}const L=(d-1)*Bt;re(L),_s(L)}}),ie&&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:[H&&H.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:At,onClick:()=>{Hi()},children:At?"Requesting…":`Request indexing (${H.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:()=>{Oa(!0)},children:lt?"Loading…":"Reload saved coverage"})]})]}),H&&H.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const d=H.summary.indexed+H.summary.notIndexed,L=d>0?H.summary.indexed/d:0,W=d>0?H.summary.notIndexed/d:0,ae=54,$e=2*Math.PI*ae,qe=$e*(1-L),Ke=$e*W,ct=$e*L;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:ae,fill:"none",stroke:It.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ae,fill:"none",stroke:gs.positiveDeep,strokeWidth:"14",strokeDasharray:$e,strokeDashoffset:qe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),H.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ae,fill:"none",stroke:It.textFaint,strokeWidth:"14",strokeDasharray:`${Ke} ${$e-Ke}`,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:[(L*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:H.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:H.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(H.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(H.reasonGroups??[]).length," ",(H.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),H.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:H.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(d=>{const L=d==="indexed"?H.indexed.length:d==="notIndexed"?H.notIndexed.length:H.deindexed.length,W=d==="indexed"?"Indexed":d==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Ze===d,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Ze===d?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{qs(d),Ht(null)},children:[W," (",L,")"]},d)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ze==="indexed"&&H.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:Re.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.crawlTime?d.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.isMobileFriendly===!0?"Yes":d.isMobileFriendly===!1?"No":"—"})]},d.id))})]}),Ze==="notIndexed"&&!st&&(H.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:(H.reasonGroups??[]).map(d=>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:()=>Ht(d.reason),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),Ht(d.reason))},tabIndex:0,role:"button","aria-label":`View ${d.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:d.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.count})]},d.reason))})]}),Ze==="notIndexed"&&!st&&(H.reasonGroups??[]).length===0&&H.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:Wt.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"})]},d.id))})]}),Ze==="notIndexed"&&st&&(()=>{const d=(H.reasonGroups??[]).find(L=>L.reason===st);return d?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:()=>Ht(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:d.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[d.count," affected page",d.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:At,onClick:()=>{Fa(d.urls.map(L=>L.url))},children:At?"Requesting…":`Request indexing (${d.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Fs.map(L=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:L.url}),e.jsx("td",{className:"text-secondary",children:L.crawlTime?L.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:At,onClick:()=>{Fa([L.url])},title:"Request indexing",children:"Index"})})]},L.id))})]})]}):null})(),Ze==="deindexed"&&H.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:xt.map((d,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState}),e.jsx("td",{className:"text-secondary",children:d.currentState}),e.jsx("td",{className:"text-secondary",children:d.transitionDate.split("T")[0]})]},`${d.url}-${L}`))})]}),(Ze==="indexed"&&H.indexed.length===0||Ze==="notIndexed"&&!st&&H.notIndexed.length===0||Ze==="deindexed"&&H.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ps,{page:ee,pageSize:Zt,visibleRows:Math.min(Zt,B.length-se),totalRows:B.length,onPageChange:ge,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Dt,onClick:()=>Es(d=>!d),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Dt?"Hide snapshots":yt.length>0?`View ${yt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",H.summary.indexed.toLocaleString()," indexed, ",H.summary.notIndexed.toLocaleString()," not indexed.",ye&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ye.indexed>=0?"+":"",ye.indexed.toLocaleString()," indexed, ",ye.notIndexed>=0?"+":"",ye.notIndexed.toLocaleString()," not indexed."]})]}),Dt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:yt.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:yt.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.notIndexed.toLocaleString()})]},d.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:lt?"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:ke||!wt?.propertyId,onClick:()=>{Un()},children:ke?"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:me,onChange:d=>fe(d.target.value),onKeyDown:d=>d.key==="Enter"&&void Ns([me.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!os||tt||!me.trim(),onClick:()=>{Ns([me.trim()])},children:tt?"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:!os||tt||qn.length===0,onClick:()=>{Ns(qn)},children:tt?"Resubmitting…":zi}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!os||tt||!ht?.length,onClick:()=>{Yi()},children:"Resubmit all files"}),We&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",We.indexes," index",We.indexes===1?"":"es",", ",We.files," file",We.files===1?"":"s"]}),E&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",E.completed,"/",E.total]})]}),!os&&wt&&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:Ie(Va),children:"Reconnect"})]}),ht&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ht.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ys,{value:pt,onChange:d=>{Je(d),Et.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:Et.rows.flatMap(d=>{const L=dr(d),W=ur(d),ae=mr(d),$e=ot[d.path]??[],qe=Le.has(d.path),Ke=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Cn,{value:d.path})}),e.jsx("td",{className:"text-secondary",children:d.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":qe,"aria-label":`${qe?"Collapse":"Expand"} files in ${d.path}`,onClick:()=>{Wi(d.path)},children:Tt.has(d.path)?"Loading…":`${qe?"▾":"▸"} Index${ot[d.path]?` (${$e.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ae}),e.jsx("td",{className:"text-secondary",children:d.lastSubmitted?d.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.lastDownloaded?d.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:L.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:W||"—"}),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:!os||tt,onClick:()=>{Ns([d.path])},children:d.lastSubmitted?"Resubmit to Google":"Submit to Google"}),wt?.sitemapUrl===d.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:kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{_a(d.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Fn.isPending,onClick:()=>{Ua(d.path)},children:"Inspect URLs"})]})})]},d.path),ct=d.isSitemapsIndex&&qe?$e.map(ne=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Cn,{value:ne.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:mr(ne)}),e.jsx("td",{className:"text-secondary",children:ne.lastSubmitted?ne.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ne.lastDownloaded?ne.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:dr(ne).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:ur(ne)||"—"}),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:!os||tt,onClick:()=>{Ns([ne.path])},children:"Resubmit"}),wt?.sitemapUrl===ne.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:kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{_a(ne.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Fn.isPending,onClick:()=>{Ua(ne.path)},children:"Inspect URLs"})]})})]},`${d.path}:${ne.path}`)):[];return[Ke,...ct]})})]}),e.jsx(Ps,{page:Et.page,pageSize:Bt,visibleRows:Et.rows.length,totalRows:Et.totalRows,onPageChange:Et.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:g,onChange:d=>v(d.target.value),onKeyDown:d=>d.key==="Enter"&&void za()}),e.jsx(A,{type:"button",size:"sm",disabled:be||!wt?.propertyId||!g.trim(),onClick:Ie(za),children:be?"Inspecting…":"Inspect URL"})]}),T&&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:T.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:T.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:Qa(T.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:Ot(T.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:R,onClick:()=>{mn(!0)},children:R?"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:Xe,onChange:d=>rt(d.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:R,onClick:()=>{mn(!0)},children:"Apply filter"})]}),N.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:N.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-neutral",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Qa(d.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ot(d.inspectedAt)})]},d.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"})]})}),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:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:b.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:d.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ot(d.transitionDate)})]},`${d.url}:${d.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),wt&&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:()=>Ds(d=>!d),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 ${is?"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"})]})}),is&&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:O,disabled:Ve||m.length===0,onChange:d=>$(d.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ve?"Loading properties…":"No properties available"}):m.map(d=>e.jsxs("option",{value:d.siteUrl,children:[d.siteUrl," · ",d.permissionLevel]},d.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Ve,onClick:()=>{qa(wt,!0)},children:Ve?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!O||He,onClick:Ie(Ji),children:He?"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:C,onChange:d=>J(d.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:z,onChange:d=>P(d.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:On.isPending||!wt.propertyId,onClick:Ie(Zi),children:On.isPending?"Queueing…":"Queue sync"}),!wt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const tu=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function su({projectName:t,projectId:s}){const n=rs(),[a,r]=l.useState(null),[i,o]=l.useState(null),[m,u]=l.useState(!1),h=_e(Na({client:V,path:{name:t}})),x=h.data?.find(q=>q.connectionType==="gbp"),c=!!x,y=a?{locationName:a}:void 0,N=_e({...Ml({client:V,path:{name:t}}),enabled:c}),f=_e({...Dl({client:V,path:{name:t},query:y}),enabled:c}),b=_e({...El({client:V,path:{name:t},query:y}),enabled:c}),p=_e({...ql({client:V,path:{name:t},query:y}),enabled:c}),T=_e({...Ol({client:V,path:{name:t},query:y}),enabled:c}),_=_e({...Fl({client:V,path:{name:t},query:y}),enabled:c}),O=_e({queryKey:["gbp-section-insights",t],queryFn:()=>_l(t),enabled:c});function $(){at(n,"gbp")}const g=Zs({...Gl(),onSuccess:q=>{Ul({id:q.runId,projectId:s,kind:en["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),we({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(Bl,Wa,Wa),C=Object.values(v.runs).some(q=>q.kind===en["gbp-sync"]&&q.projectId===s),J=g.isPending||C,z=Zs({...Kl(),onSuccess:()=>$()});if(l.useEffect(()=>{if(!a||!N.data)return;const q=N.data.locations.filter(ie=>ie.selected);(q.length<=1||!q.some(ie=>ie.locationName===a))&&r(null)},[a,N.data]),l.useEffect(()=>{if(!i||!N.data)return;(a?[a]:N.data.locations.filter(ie=>ie.selected).map(ie=>ie.locationName)).includes(i)||o(null)},[i,N.data,a]),h.isLoading)return null;if(!x){const q=[{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:q.map((ie,Se)=>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:Se+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ie.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:ie.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ie.note})]})]},ie.title))})]})})}const P=f.data,k=N.data?.locations??[],U=k.filter(q=>q.selected),M=b.data?.keywords??[],te=p.data?.lodging??[],je=T.data?.placeActions??[],le=_.data?.places??[],Q=k.length>0?k[0].accountName:x.domain,de=a?k.find(q=>q.locationName===a)?.displayName??null:null,oe=a?k.filter(q=>q.locationName===a):U,G=new Set(oe.map(q=>q.locationName)),F=te.filter(q=>G.has(q.locationName)),w=je.filter(q=>G.has(q.locationName)),Z=le.filter(q=>G.has(q.locationName)),re=new Set(U.map(q=>q.locationName)),ce=a?M:M.filter(q=>re.has(q.locationName)),K=!a&&U.length>1,xe=(O.data??[]).filter(q=>!q.dismissed&&tu.has(q.type)&&(!de||q.query===de||q.query===a||q.title.startsWith(de)));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(ue,{tone:"positive",children:"Connected"}),!Y()&&e.jsx(et,{type:"button",variant:"outline",size:"sm",disabled:J,onClick:()=>g.mutate({client:V,path:{name:t},body:{}}),children:J?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[Q?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:Q})," · "]}):null,N.data?`${N.data.totalSelected} of ${N.data.totalDiscovered} locations tracked`:"Loading locations…"]}),U.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:q=>r(q.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),U.map(q=>e.jsx("option",{value:q.locationName,children:q.displayName},q.id))]})]}),U.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[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(q=>e.jsx("div",{className:["insight-card",pu(q.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:[q.title,q.recommendation?.reason&&e.jsx(ze,{text:q.recommendation.reason})]})},q.id))]}),P&&e.jsx(yu,{performance:P.performance,freshness:P.freshness,timeseries:P.timeseries}),P?.profileCompleteness&&e.jsx(nu,{summary:P.profileCompleteness}),oe.length>0&&e.jsx(au,{locations:oe,lodging:F,places:Z,placeActions:w,expandedLocation:i,onToggleExpanded:q=>{o(ie=>ie===q?null:q)}}),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"}),b.data&&b.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[b.data.thresholdedPct,"% privacy-thresholded"]})]}),ce.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"}),K&&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:ce.slice(0,25).map(q=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:q.keyword}),K&&e.jsx("td",{className:"text-muted",children:k.find(ie=>ie.locationName===q.locationName)?.displayName??q.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:q.valueCount!==null?q.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",q.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[q.periodStart,"–",q.periodEnd]})]},`${q.locationName}:${q.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>u(q=>!q),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",k.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:k.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"}),!Y()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:k.map(q=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:q.displayName}),e.jsx("td",{className:"text-muted",children:q.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ue,{tone:q.selected?"positive":"neutral",children:q.selected?"Tracked":"Not tracked"})}),!Y()&&e.jsx("td",{className:"text-right",children:e.jsx(et,{type:"button",variant:"outline",size:"sm",disabled:z.isPending,onClick:()=>z.mutate({client:V,path:{name:t,locationName:q.locationName},body:{selected:!q.selected}}),children:q.selected?"Untrack":"Track"})})]},q.id))})]})})]})]})})}function nu({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Bs(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Bs(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Bs(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Bs(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Bs(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 ${xu(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function au({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:i}){const o=new Map(s.map(h=>[h.locationName,h])),m=new Map(n.map(h=>[h.locationName,h])),u=new Map;for(const h of a){const x=u.get(h.locationName)??[];x.push(h),u.set(h.locationName,x)}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:Y()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const x=o.get(h.locationName)??null,c=m.get(h.locationName)??null,y=u.get(h.locationName)??[],N=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ue,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ue,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ci(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(iu,{location:h})}),e.jsx("td",{children:e.jsx(lu,{lodging:x})}),e.jsx("td",{children:e.jsx(cu,{place:c,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(uu,{actions:y})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>i(h.locationName),children:N?"Hide":"Details"})})]}),N&&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(hu,{location:h,lodging:x,place:c,placeActions:y})})})]},h.id)})})]})})]})}function ru(t){return[{label:"Description",tone:ms(t.description)?"positive":"neutral",value:ms(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:ms(t.primaryPhone)?"positive":"neutral",value:ms(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:ms(t.websiteUri)?"positive":"neutral",value:ms(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function iu({location:t}){const s=ru(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ue,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function lu({lodging:t}){return e.jsx(Sa,{...ou(t)})}function ou(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 cu({place:t,mapsUri:s}){return e.jsx(Sa,{...du(t,s)})}function du(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 uu({actions:t}){return e.jsx(Sa,{...mu(t)})}function mu(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 Sa({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ue,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function hu({location:t,lodging:s,place:n,placeActions:a}){const r=s?fu(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Wn,{title:"Owner profile · Business Information",children:[e.jsx(gt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(gt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(gt,{label:"Description",value:ms(t.description)?t.description:"Not returned"}),e.jsx(gt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(gt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(gt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(gt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(gt,{label:"Open status",value:Ci(t.openStatus)}),e.jsx(gt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Wn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(gt,{label:"Last checked",value:hr(s.syncedAt)}),e.jsx(gt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(gt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(Wn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(gt,{label:"Places tier",value:n.tier}),e.jsx(gt,{label:"Last checked",value:hr(n.syncedAt)}),e.jsx(gt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(i=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Mn(i.placeActionType),i.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Mn(i.providerType),i.uri?` · ${gu(i.uri)}`:""]})]},i.placeActionLinkName))})})]})]})}function Wn({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function gt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function Bs(t,s,n){return t===s?"positive":t===0?n:"caution"}function xu(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function pu(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function ms(t){return typeof t=="string"&&t.trim().length>0}function Ci(t){return t?Mn(t):"Not returned"}function Mn(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function gu(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function hr(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function fu(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&bu(n)).map(([s])=>Mn(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function bu(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function yu({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Vl.filter(f=>(a[f]??0)>0),i=zl.filter(f=>(a[f]??0)>0),o=Object.keys(a).filter(f=>(a[f]??0)>0&&Ql(f)==="other").sort((f,b)=>(a[b]??0)-(a[f]??0)),m=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),u=n.map(f=>{const b={date:f.date};for(const[p,T]of Object.entries(f.metrics))b[p]=T;return b}),h=n.find(f=>f.pending)?.date,x=n.length>0?n[n.length-1].date:void 0,c=u.length>0,y=s.dataThroughDate?`Data through ${ps(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,N=[...r,...o];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),y&&e.jsx("span",{className:"text-[11px] text-muted",children:y})]}),!c||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(xr,{data:u,metrics:r,kind:"line",firstPending:h,lastDate:x}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:N.map(f=>e.jsxs("span",{className:"text-sm text-secondary",children:[An(f)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[f]??0).toLocaleString()})]},f))})]})]}),c&&i.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(xr,{data:u,metrics:i,kind:"area",firstPending:h,lastDate:x})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(f=>An(f)).join(", ")]})]})}function xr({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ci,{stroke:ii,vertical:!1}),e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn,minTickGap:24}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(i,o)=>[typeof i=="number"?i.toLocaleString():String(i??0),An(String(o??""))]}),e.jsx(oi,{wrapperStyle:{fontSize:11,color:It.text},formatter:i=>An(i)}),a&&r&&e.jsx(rd,{x1:a,x2:r,fill:It.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:It.textDim,fontSize:10}}),s.map((i,o)=>n==="line"?e.jsx(di,{type:"monotone",dataKey:i,stroke:mt[o%mt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},i):e.jsx(Cs,{type:"monotone",dataKey:i,stackId:"reach",stroke:mt[o%mt.length],fill:mt[o%mt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},i))]})})})}function ju(t){return li(as(String(t)))}function vu(t){return fs(as(String(t)))}function Yn({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[i,o]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":i?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:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Yc,{className:"h-3.5 w-3.5","aria-hidden":!0})}),i&&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 yn=Bt;function ws(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Xn(t){return t.toLocaleString()}function Nu(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function wu(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 Su(t){const s=t.filter(n=>n.kind===en["backlink-extract"]&&!Xr(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Cu(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),i=a%60;return i===0?`${r}m`:`${r}m ${i}s`}function ku({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[i,o]=l.useState([]),[m,u]=l.useState(null),[h,x]=l.useState(null),[c,y]=l.useState(null),[N,f]=l.useState(Date.now()),[b,p]=l.useState(0),[T,_]=l.useState(!0),[O,$]=l.useState(!1),[g,v]=l.useState(null),C=l.useCallback(async()=>{_(!0),v(null);try{const[Q,de,oe,G,F]=await Promise.all([Hl().catch(()=>null),Wl(t,{excludeCrawlers:!0}).catch(()=>null),Yl(t,{limit:yn,offset:b,excludeCrawlers:!0}).catch(Z=>{if(Z instanceof Ls&&Z.code==="NOT_FOUND")return null;throw Z}),Xl(t).catch(()=>[]),Jl(t).catch(()=>[])]);u(Q),n(de),r(oe),o(G);const w=Su(F);x(w)}catch(Q){v(Q instanceof Error?Q.message:"Failed to load backlinks")}finally{_(!1)}},[t,b]);l.useEffect(()=>{C()},[C]),l.useEffect(()=>{if(!h)return;const Q=h.id;let de=!1;const oe=async()=>{try{const F=await ua(Q);if(de)return;Xr(F.status)?(x(null),y(F),await C()):x(w=>w?.id===F.id?{...w,...F}:w)}catch{}},G=window.setInterval(()=>{oe()},3e3);return()=>{de=!0,window.clearInterval(G)}},[h,C]),l.useEffect(()=>{if(!h)return;const Q=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(Q)},[h]),l.useEffect(()=>{if(!c||c.status==="failed")return;const Q=window.setTimeout(()=>y(null),1e4);return()=>window.clearTimeout(Q)},[c]);async function J(){$(!0),v(null);try{const Q=await eo(t);x(Q)}catch(Q){Q instanceof Ls&&Q.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(Q instanceof Error?Q.message:"Failed to trigger extract")}finally{$(!1)}}const z=l.useMemo(()=>i.slice().sort((Q,de)=>Q.queriedAt.localeCompare(de.queriedAt)).map(Q=>({date:Q.queriedAt,linkingDomains:Q.totalLinkingDomains})),[i]),P=a?.rows??[],k=a?.total??0,U=s?.excludedLinkingDomains??0,M=Math.floor(b/yn)+1;return l.useEffect(()=>{b>0&&b>=k&&p(0)},[b,k]),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"})]})}),g&&e.jsx(he,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:g})}),h&&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(Hc,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(ue,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Cu(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",N]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),c&&!h&&e.jsx(he,{className:`surface-card p-4 mb-4 ${c.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[c.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(ai,{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 ${c.status==="failed"?"text-negative":"text-positive"}`,children:c.status==="failed"?"Extract failed":"Extract complete"}),c.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Zl(c.error)}):c.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),te()]});function te(){return T?e.jsx(he,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):je()}function je(){const Q=s!==null&&s.totalLinkingDomains>0,de=c?.status==="failed",oe=s!==null&&s.totalLinkingDomains===0&&!de,G=m?.status==="ready",F=m?.status==="failed",w=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return Q?le(e.jsxs(e.Fragment,{children:[!Y()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(ri,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Re-run extract"]}),e.jsx(Yn,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!Y()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/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(Wc,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Set up backlinks"})})})]}),w&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"View sync status"})})})]}),F&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),G&&!w&&!oe&&!de&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:m.release})," is ready. Run an extract for this project."]}),!Y()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(In,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Run extract"]}),e.jsx(Yn,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),de&&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."}),!Y()&&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:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!Y()&&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:ws("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(In,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Re-run extract"]}),e.jsxs(Yn,{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 le(Q){if(!s)return null;const de="Linking hosts",oe="linking hosts",G="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:Xn(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Xn(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Nu(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",G," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",wu(s.queriedAt),U>0&&e.jsxs(e.Fragment,{children:[" · ",U," excluded domain",U===1?"":"s"]})]}),z.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(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:z,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:mt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:mt[0],stopOpacity:0})]})}),e.jsx(nn,{dataKey:"date",tick:Ft,stroke:bs,tickFormatter:ju}),e.jsx(an,{tick:Ft,stroke:bs,allowDecimals:!1}),e.jsx(rn,{contentStyle:As.contentStyle,labelStyle:As.labelStyle,itemStyle:As.itemStyle,labelFormatter:vu}),e.jsx(Cs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:mt[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:de})]})}),e.jsxs("tbody",{children:[P.map(F=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:F.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Xn(F.numHosts)})]},F.linkingDomain)),P.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:U>0&&k===0?`Every referring domain in this ${G} was a crawler/proxy host (${U} hidden).`:`No referring domains in this ${G}.`})})]})]})}),e.jsx(Ps,{page:M,pageSize:yn,visibleRows:P.length,totalRows:k,onPageChange:F=>p((F-1)*yn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:Q})]})}}function Pu({projectName:t}){const s=_e({...to({client:V,path:{name:t}}),staleTime:Jr}),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:wa(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:i,providersConfigured:o}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",o," 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 ",i," of ",o," 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(Au,{data:n}),e.jsx(Ru,{data:n}),n.competitorGaps.length>0&&e.jsx(Tu,{data:n})]})}function Au({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:i}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(jn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(jn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(jn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(jn,{label:"Invisible",value:`${i} / ${s}`,helper:"No engine cites or mentions",tone:i>0?"negative":"neutral"})]})}function jn({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 Ru({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($u,{}),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(Is,{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(i=>i.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(Xc,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Iu,{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 $u(){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(ks,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ks,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ks,{active:!1,tone:"cited"}),e.jsx(ks,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Iu({provider:t}){const s=Lu(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(ks,{active:t.cited,tone:"cited"}),e.jsx(ks,{active:t.mentioned,tone:"mentioned"})]})}function Lu(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 ks({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 Tu({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(Is,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const cn="__cited__",dn="__mentioned__",$t="__mentionShare__";function ki(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:as(n),end:as(a),sweepCount:s.sweepCount??1}}function Dn(t){const s=ki(t);if(!s)return"Sweep date unavailable";const n=fs(s.start),a=fs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Mu(t){const s=ki(t);return s?li(s.start):""}function Ms(t){return t.trim().toLowerCase()}function pa(t){return Math.round(t*1e3)/10}function ga(t){return t.byProvider??{}}function Du(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const u=s==="cited"?cn:dn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(c=>({date:c.startDate,[u]:pa(c[h])})),series:[u],hasData:a,singleBucket:r}}const i=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(u=>Object.keys(ga(u))))].sort();return{rows:t.buckets.map(u=>{const h={date:u.startDate},x=ga(u);for(const c of o){const y=x[c];h[c]=y?pa(y[i]):null}return h}),series:o,hasData:a,singleBucket:r}}function Pi(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Eu(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function qu(t){return t.servedModelAttribution??{}}function Ou(t){return t.modelServiceMismatch??{}}function Fu(t){return t.modelPointerChanges??{}}function _u(t){return t.length>0?t.join(", "):null}function pr(t,s){const n=Ms(s);return Object.entries(t).find(([a])=>Ms(a)===n)?.[1]}function Kt(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 Uu(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!pr(ga(a),s))continue;const r=Pi(a);return r?pr(r,s)??null:null}return null}function Gu(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const i=s.get(r.bucketStartDate)??[];i.push({provider:n,event:r}),s.set(r.bucketStartDate,i)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,i)=>r.provider.localeCompare(i.provider)||r.event.observedAt.localeCompare(i.event.observedAt))}))}function Bu(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const i=r.events.filter(o=>!o.fromPreWindowAnchor);for(const o of r.events)o.fromPreWindowAnchor&&n.push({provider:a,event:o});i.length>0&&(s[a]={...r,events:i})}return{buckets:Gu(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Ku(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 Vu(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 zu(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[$t]:r?.rate==null?null:pa(r.rate)}}),n=s.map(a=>a[$t]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[$t],hasData:n.length>0,singleBucket:n.length===1}}function Qu(t,s,n){return s==="mentionShare"?zu(t):Du(t,s,n)}function gr(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 fr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function br(t){return t>0?`+${t}`:`${t}`}function Hu(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${br(n.delta)} on ${fr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${br(s.delta)} on ${fr(s.date)})`}const Wu=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Yu=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Xu=[{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:"Of all answer-text brand mentions for you and tracked competitors, the share that were you."}],Ca=mt[2],Ju="var(--chart-tooltip-bg)",Zu={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function zt(t){const s=Ms(t);return Zu[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ss(t){return Math.round(t*10)/10}function em(t){return t===cn||t===dn||t===$t}function Ai(t){return t===cn?"Cited":t===dn?"Mentioned":t===$t?"Mention share":zt(t)}function zs(t,s){return t===cn?gs.positive:t===dn?mt[1]:t===$t?Ca:td(Ms(t),s)}function tm(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function sm(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
+
`)}function Pn(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function ln(t){return t==="cited"?"citationRate":"mentionRate"}function Ri(t,s){return s==="cited"?t.cited:t.mentionedCount}function $i(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 Ii(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function fa(t){const s=Pi(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>Ms(a).localeCompare(Ms(r))).map(([a,r])=>`${zt(a)}: ${Kt(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function nm(t){return t.some(({event:s})=>s.to.status==="mixed")?gs.caution:t.some(({event:s})=>s.to.status==="unknown")?gs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?mt[4]:gs.positive}function am(t,s,n){const a=Ii(t,s);return a?Dn(a):fs(as(n))}function rm({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:i,mismatch:o,buckets:m}){const u=l.useId(),h=Object.entries(i).sort(([c],[y])=>c.localeCompare(y)),x=t.buckets.length>0||t.beforeWindow.length>0;return e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":u,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:u,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),s?x?e.jsxs(e.Fragment,{children:[t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:c,events:y})=>y.map(({provider:N,event:f})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:am(m,c,f.observedAt)}),e.jsxs("span",{children:[zt(N),": ",Kt(f.from)," → ",Kt(f.to)]})]},`${N}-${f.observedAt}-${f.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:c,event:y})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",fs(as(y.observedAt))]}),e.jsxs("span",{children:[zt(c),": ",Kt(y.from)," → ",Kt(y.to),y.anchorObservedAt?` (last seen ${Kt(y.from)} on ${fs(as(y.anchorObservedAt))})`:""]})]},`before-${c}-${y.observedAt}`))})]}),a.map(c=>e.jsxs("p",{className:"trend-model-evidence-note",children:[zt(c.provider),": showing the most recent ",c.shown," of ",c.total," changes."]},`truncated-${c.provider}`)),r.map(c=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",zt(c)," change."]},`incomplete-${c}`))]}):e.jsx("p",{className:"trend-model-evidence-empty",children:"No model evidence changes in this window."}):e.jsx("p",{className:"trend-model-evidence-empty",children:"Attribution unavailable from this API version."}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([c,y])=>{const N=_u(y.latestServedModelIds),f=o[c];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:fs(as(y.latestObservation.observedAt))}),e.jsxs("span",{children:[zt(c),": ",N??Kt(y.latestObservation.state),f?` — not the ${Kt(f.configured)} you selected`:""]})]},`served-${c}`)})})]})]})}function yr(t){return t===null?"no data":`${t}%`}function Jn(t){return t==null?"undefined":`${ss(t*100)}%`}function im({active:t,label:s,payload:n,metric:a,mode:r,buckets:i}){if(!t)return null;const o=Ii(i,s);if(!o)return null;if(a==="mentionShare"){const u=o.mentionShare.projectMentionSnapshots,h=o.mentionShare.competitorMentionSnapshots,x=u+h,c=o.mentionShare.rate==null?null:ss(o.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Dn(o)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Ca},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:"Mention share"}),e.jsx("span",{className:"trend-tooltip-value",children:yr(c)})]}),x>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",u," / ",x," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:fa(o)})]})}const m=r==="byProvider"?(n??[]).filter(u=>u.dataKey!==void 0):[{dataKey:a==="cited"?cn:dn,value:ss(o[ln(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Dn(o)}),m.map((u,h)=>{const x=String(u.dataKey??u.name??""),c=r==="byProvider"?$i(o,x,a):null,y=c?.count??Ri(o,a),N=c?.total??o.total,f=typeof u.value=="number"?u.value:ss(c?c.rate*100:o[ln(a)]*100),b=u.color??zs(x,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:b},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ai(x)}),e.jsx("span",{className:"trend-tooltip-value",children:yr(f)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[y," / ",N," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${x}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:fa(o)})]})}function lm({buckets:t,metric:s,mode:n,series:a}){return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Pn(s)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(r=>{let i;if(s==="mentionShare"){const o=r.mentionShare.projectMentionSnapshots,m=r.mentionShare.competitorMentionSnapshots,u=o+m;i=u>0?`${Jn(r.mentionShare.rate)} mention share, ${o} of ${u} brand mentions were you`:"mention share undefined, no project or competitor brand mentions"}else n==="byProvider"?i=a.map(o=>{const m=$i(r,o,s);return m?`${zt(o)} ${Jn(m.rate)} ${Pn(s).toLowerCase()}, ${m.count} of ${m.total} snapshots`:`${zt(o)} no data`}).join("; "):i=`${Jn(r[ln(s)])} ${Pn(s).toLowerCase()}, ${Ri(r,s)} of ${r.total} snapshots`;return i+=`; ${fa(r)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Dn(r)}),e.jsx("td",{children:i})]},r.startDate)})})]})}function Zn({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const i=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(o=>{const m=s===o.value,u=o.description?`${i}-${o.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":m,"aria-describedby":u,className:`segmented-option ${m?"segmented-option-active":""}`,onClick:()=>n(o.value),children:o.label}),o.description&&e.jsx("span",{id:u,className:"sr-only",children:o.description})]},o.value)})})}function om({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[i,o]=l.useState("mentioned"),[m,u]=l.useState("byProvider"),h=l.useMemo(()=>sm(s),[s]),x=_e({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>so(t,a),staleTime:Jr}),c=x.data??null,y=x.error,N=i==="mentionShare"?"overall":m,f=l.useMemo(()=>c?Qu(c,i,N):null,[c,i,N]),b=c?Eu(c):null,p=l.useMemo(()=>Bu(b??{}),[b]),T=l.useMemo(()=>Ku(b??{}),[b]),_=l.useMemo(()=>Vu(b??{}),[b]),O=l.useMemo(()=>Object.entries(b??{}).filter(([,G])=>G.anchorUnavailable).map(([G])=>G).sort(),[b]),$=l.useMemo(()=>c?qu(c):{},[c]),g=l.useMemo(()=>c?Ou(c):{},[c]),v=l.useMemo(()=>c?no(Fu(c)):null,[c]),C=i!=="mentionShare"&&N==="byProvider",J=Pn(i),z=i==="cited"?gs.positive:i==="mentionShare"?Ca:mt[1],P=C?It.textDim:z,k=c?.buckets??[],U=l.useMemo(()=>{const G=new Map(k.map(F=>[F.startDate,Mu(F)]));return F=>G.get(String(F))??""},[k]),M=i==="mentionShare"?f?gr(f.rows,$t):null:k.length>0?ss(k[k.length-1][ln(i)]*100):null,te=i==="mentionShare"?f?tm(f.rows,$t):null:k.length>0?ss(k[0][ln(i)]*100):null,je=i==="mentionShare"?f?.rows.filter(G=>typeof G[$t]=="number").length??0:k.length,le=M!==null&&te!==null&&je>1?ss(M-te):null,Q=s.length,de=e.jsxs(e.Fragment,{children:[v?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:v.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(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 query-provider snapshot rates; Mention share uses project plus competitor brand mentions."})]})]}),M!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:P},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:J}),C&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[M,"%"]}),le!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${le>0?"text-positive-400":le<0?"text-negative-400":"text-muted"}`,children:[le>0?"+":"",le.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Zn,{options:Xu,value:i,onChange:o,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),i!=="mentionShare"&&e.jsx(Zn,{options:Yu,value:m,onChange:u,ariaLabel:"Series"}),e.jsx(Zn,{options:Wu,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]}),v?.kind==="no-known-change"&&e.jsxs("p",{className:"mt-3 text-[11px] leading-snug text-muted",children:[v.text,e.jsx(ze,{text:v.detail})]})]});let oe;if(y)oe=e.jsx("p",{className:"text-sm text-negative-400",children:wa(y)});else if(x.isLoading&&!c)oe=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(i==="mentionShare"&&Q===0)oe=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!c||!f)oe=null;else{const{rows:G,series:F,hasData:w,singleBucket:Z}=f,re=Hu(c.queryChanges);if(!w)oe=e.jsx("p",{className:"text-sm text-secondary",children:i==="mentionShare"?"No answer-text brand mentions for you or tracked competitors in this window yet.":"Run a sweep to start tracking citations and mentions over time."});else if(C&&F.length===0)oe=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 ce=`${J} rate across ${G.length} ${G.length===1?"sweep":"sweeps"}. Latest ${M}%${le!==null?`, ${le>=0?"up":"down"} ${Math.abs(le).toFixed(1)} points over the period`:""}.`;oe=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:ce}),e.jsx(lm,{buckets:k,metric:i,mode:N,series:F}),C&&F.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:F.map((K,xe)=>{const q=gr(G,K),ie=Uu(k,K),Se=b===null?"Attribution unavailable":ie?Kt(ie):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:zs(K,xe)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Ai(K)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),Se]})]}),q!==null&&e.jsxs("span",{className:"trend-legend-value",children:[q,"%"]})]},K)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${J} trend chart over ${G.length} ${G.length===1?"bucket":"buckets"}`,children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:G,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ci,{stroke:ii,vertical:!1}),e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:U,minTickGap:24}),e.jsx(an,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:K=>`${K}%`,tick:Ft,tickLine:!1,axisLine:!1,width:40}),e.jsx(rn,{cursor:{stroke:bs,strokeWidth:1},content:e.jsx(im,{metric:i,mode:N,buckets:k})}),p.buckets.map(({bucketStartDate:K,events:xe})=>e.jsx(id,{x:K,stroke:nm(xe),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${K}`)),F.map((K,xe)=>e.jsx(di,{type:"monotone",dataKey:K,name:K,stroke:zs(K,xe),strokeDasharray:K===$t?"5 4":void 0,strokeWidth:em(K)?2.5:2,dot:K===$t?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:zs(K,xe),strokeWidth:1.5}:{r:2.5,fill:zs(K,xe),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Ju},connectNulls:K!==$t,isAnimationActive:!1},K))]})})}),e.jsx(rm,{partition:p,available:b!==null,counts:T,truncated:_,incompleteHistory:O,served:$,mismatch:g,buckets:k}),Z&&e.jsx("p",{className:"visibility-trend-note",children:i==="mentionShare"?"Only one competitive mention-share point so far. The trend line fills in after another sweep with brand mentions.":"Only one sweep so far. The trend line fills in after the next run."}),re&&e.jsx("p",{className:"visibility-trend-note",children:re})]})}}return e.jsxs("section",{className:"visibility-trend",children:[de,oe]})}const jr=new Set([Ws.queued,Ws.running]);function cm({projectName:t}){const s=rs(),[n,a]=l.useState(""),[r,i]=l.useState(""),[o,m]=l.useState(""),[u,h]=l.useState("__default__"),[x,c]=l.useState(null),y=_e({...ao({client:V,path:{name:t}}),staleTime:6e4}),N=_e({...Zr({client:V}),staleTime:6e4}),f=_e({...ro({client:V,path:{name:t},query:{limit:20}}),refetchInterval:P=>P.state.data?.runs.some(k=>jr.has(k.status))?3e3:!1}),b=f.data?.runs??[];l.useEffect(()=>{!x&&b[0]&&c(b[0].id)},[b,x]);const p=b.find(P=>P.id===x)??null,T=_e({...io({client:V,path:{name:t,runId:x??""}}),enabled:!!x,refetchInterval:p&&jr.has(p.status)?3e3:!1}),_=T.data??null,O=l.useMemo(()=>mm(n),[n]),$=y.data?.locations??[],g=l.useMemo(()=>{const P=new Map((N.data?.providerCatalog??[]).map(k=>[k.name,k]));return(N.data?.providers??[]).filter(k=>k.configured&&P.get(k.name)?.mode==="api").map(k=>({...k,catalog:P.get(k.name)}))},[N.data]),v=!N.isLoading&&g.length===0,C=g.find(P=>P.name===r)??null;l.useEffect(()=>{r&&!C&&(i(""),m(""))},[r,C]);const J=Zs({...lo(),onSuccess:async P=>{c(P.id),a(""),m(""),await gm(s),we({title:"Research batch saved",detail:`${P.totalQueries} quer${P.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${P.id}`,dedupeMode:"replace"})},onError:P=>{we({title:"Could not start research",detail:P instanceof Error?P.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function z(){if(O.length===0||O.length>50||v||J.isPending||Y())return;const P=u==="__default__"?void 0:u==="__none__"?null:$.find(k=>k.label===u)??void 0;J.mutate({client:V,path:{name:t},body:{queries:O,...r?{provider:r}:{},...r&&o.trim()?{model:o.trim()}:{},...P!==void 0?{location:P}:{}}})}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:P=>a(P.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${O.length>50?"text-negative":"text-faint"}`,children:[O.length," ",O.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:P=>{i(P.target.value),m("")},children:[e.jsx("option",{value:"",children:"Project default"}),g.map(P=>e.jsx("option",{value:P.name,children:P.displayName??P.name},P.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:u,onChange:P=>h(P.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),$.map(P=>e.jsx("option",{value:P.label,children:P.label},P.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:C?`Default: ${C.model??C.defaultModel??C.catalog.defaultModel}`:"Choose a provider to select an exact model",value:o,disabled:!C,onChange:P=>m(P.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(C?.catalog.knownModels??[]).map(P=>e.jsx("option",{value:P.id,children:P.displayName},P.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!Y()&&e.jsxs(et,{type:"button",size:"sm",disabled:O.length===0||O.length>50||v||J.isPending,onClick:z,children:[e.jsx(In,{size:14}),J.isPending?"Starting research…":`Run ${O.length||""} research ${O.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"})]}),f.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),b.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:b.map(P=>e.jsxs("tr",{className:x===P.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:()=>c(P.id),children:hm(P.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:P.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:P.requestedModel??P.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:P.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[P.completedQueries+P.failedQueries,"/",P.totalQueries]}),e.jsx("td",{children:e.jsx(ue,{tone:Li(P.status),children:P.status})})]},P.id))})]})})]})]}),e.jsx(dm,{detail:_,isLoading:T.isFetching})]})}function dm({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(i=>i.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 ${xm(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(ue,{tone:Li(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:r?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(ue,{tone:pm(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ue,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===xs.failed?"negative":"caution",children:i.answerMentioned===null?i.status===xs.failed?"Unavailable":"Pending":i.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(ue,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===xs.failed?"negative":"caution",children:i.citationState===null?i.status===xs.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(um,{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 um({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===xs.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=us(n.uri),i=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:i}):e.jsx("span",{className:"truncate text-secondary",children:i}),r&&e.jsx(Jc,{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 mm(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 hm(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 xm(t){return t.length>8?t.slice(0,8):t}function Li(t){return t===Ws.completed?"positive":t===Ws.partial?"caution":t===Ws.failed?"negative":"neutral"}function pm(t){return t===xs.completed?"positive":t===xs.failed?"negative":"neutral"}async function gm(t){await at(t,"researchRuns")}const ba=new Set(["queued","seeding","probing"]);function fm({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(bm,{projectName:t}):e.jsx(cm,{projectName:t})})]})}function bm({projectName:t}){const s=rs(),[n,a]=l.useState(null),[r,i]=l.useState(""),[o,m]=l.useState("100"),u=_e({...oo({client:V,path:{name:t},query:{limit:"10"}}),refetchInterval:g=>g.state.data?.some(C=>ba.has(C.status))?3e3:!1}),h=u.data??[];l.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const x=h.find(g=>g.id===n)??null,c=_e({...co({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:x&&ba.has(x.status)?3e3:!1}),y=c.data??null,N=_e({...uo({client:V,path:{name:t,id:n??""}}),enabled:!!(n&&x?.status==="completed")}),f=Zs({mutationFn:()=>{const g={},v=r.trim();v&&(g.icpDescription=v);const C=Number.parseInt(o,10);return Number.isFinite(C)&&C>0&&(g.maxProbes=C),mo(t,g)},onSuccess:async g=>{a(g.sessionId),i(""),await Nr(s,t,g.sessionId),we({title:"Discovery started",detail:`Run ${ea(g.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${g.sessionId}`,dedupeMode:"replace"})},onError:g=>{we({title:"Discovery failed to start",detail:g instanceof Error?g.message:"Could not start discovery.",tone:"negative"})}}),b=Zs({mutationFn:g=>{if(!n)throw new Error("Select a completed discovery session first.");return ho(t,n,g)},onSuccess:async g=>{await Nr(s,t,g.sessionId),s.invalidateQueries({queryKey:ei({client:V})}),s.invalidateQueries({predicate:v=>Array.isArray(v.queryKey)&&v.queryKey[0]==="projects"&&v.queryKey.length>1}),we({title:"Queries added",detail:Nm(g),tone:"positive",dedupeKey:`discovery:promote:${g.sessionId}`,dedupeMode:"replace"})},onError:g=>{we({title:"Could not add queries",detail:g instanceof Error?g.message:"Could not add queries from this run.",tone:"negative"})}}),p=y??x,T=N.data??null,_=(T?.queriesByBucket.cited.length??0)+(T?.queriesByBucket.aspirational.length??0),O=l.useMemo(()=>(y?.probes??[]).slice(0,30),[y?.probes]);async function $(){try{const g=await u.refetch();if(g.error)throw g.error;const v=g.data?.length??0;we({title:"Discovery sessions refreshed",detail:`${v} recent session${v===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(g){we({title:"Discovery refresh failed",detail:g instanceof Error?g.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:Y()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:u.isFetching,onClick:()=>{$()},children:[e.jsx($n,{className:`size-3.5 ${u.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(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(ue,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:r,onChange:g=>i(g.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:o,onChange:g=>m(g.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."})]}),!Y()&&e.jsxs(et,{type:"button",size:"sm",disabled:f.isPending,onClick:()=>f.mutate(),children:[e.jsx(In,{size:14}),f.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"})]}),u.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),h.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:h.map(g=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===g.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(g.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:ea(g.id)}),e.jsx(ue,{tone:vr(g.status),children:g.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",g.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",g.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",g.wastedCount??0]})]})]},g.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:p?ea(p.id):"No run selected"})]}),p&&e.jsx(ue,{tone:vr(p.status),children:p.status})]}),p?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(es,{label:"Questions tested",value:p.probeCount??0}),e.jsx(es,{label:"Cited queries",value:p.citedCount??0,tone:"positive"}),e.jsx(es,{label:"Worth tracking",value:p.aspirationalCount??0,tone:"caution"}),e.jsx(es,{label:"Skip",value:p.wastedCount??0,tone:"negative"})]}),p.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:p.error}),p.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:p.warning}),p.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:p.icpDescription})]}),p.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:p.competitorMap.slice(0,8).map(g=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[g.domain," ",e.jsx("span",{className:"text-muted",children:g.hits})]},g.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),p?.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"})]}),!Y()&&e.jsxs(et,{type:"button",size:"sm",disabled:b.isPending||_===0,onClick:()=>b.mutate(void 0),children:[e.jsx(ai,{size:14}),b.isPending?"Adding…":"Add recommended queries"]})]}),N.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):T?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(es,{label:"Queries to add",value:_,tone:"positive"}),e.jsx(es,{label:"Cited queries",value:T.queriesByBucket.cited.length,tone:"positive"}),e.jsx(es,{label:"Worth tracking",value:T.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(es,{label:"Skip",value:T.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."}),T.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:T.suggestedCompetitors.map(g=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[g.domain," ",e.jsx("span",{className:"text-muted",children:g.hits})]},g.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"})]}),c.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),O.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:O.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:g.query}),e.jsx("td",{children:e.jsx(ue,{tone:ym(g.bucket),children:vm(g.bucket)})}),e.jsx("td",{className:"text-secondary",children:g.citedDomains.length>0?g.citedDomains.slice(0,3).join(", "):"-"})]},g.id))})]})})]})]})]})]})}function es({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 vr(t){return t==="completed"?"positive":t==="failed"?"negative":ba.has(t)?"caution":"neutral"}function ym(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const jm={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function vm(t){return t?jm[t]:"Not classified"}function ea(t){return t.length>8?t.slice(0,8):t}function Nm(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 Nr(t,s,n){await Promise.all([at(t,"discovery"),t.invalidateQueries({queryKey:xo({client:V})})])}function wr(t){return`${(t*100).toFixed(1)}%`}function wm({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[i,o]=l.useState(null),m=_e({...po({client:V,path:{name:t},query:{limit:30}}),enabled:s==="health"}),u=_e({...go({client:V,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(u.data??[]).filter(p=>(p.status==="completed"||p.status==="partial")&&p.trigger!=="probe").reverse(),x=i??h[0]?.id??"",c=a??h.find(p=>p.id!==x)?.id??"",y=!!(c&&x&&c!==x),N=_e({...fo({client:V,path:{name:t},query:{run1:c,run2:x}}),enabled:s==="compare"&&y}),f=m.data??[],b=N.data?.diff.filter(p=>p.changed||p.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(([p,T])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===p,className:`filter-chip ${s===p?"filter-chip-active":""}`,onClick:()=>n(p),children:T},p))}),s==="changes"?e.jsx(ld,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),m.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!m.isLoading&&f.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,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:f.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(p.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[p.mentionedPairs,"/",p.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:wr(p.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[p.citedPairs,"/",p.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:wr(p.overallCitedRate)})]},p.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:c,onChange:p=>r(p.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(p=>e.jsx("option",{value:p.id,children:new Date(p.createdAt).toLocaleString()},p.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:x,onChange:p=>o(p.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(p=>e.jsx("option",{value:p.id,children:new Date(p.createdAt).toLocaleString()},p.id))})]})]}),u.isLoading||N.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!u.isLoading&&h.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,N.data&&b.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,b.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:b.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:p.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ue,{tone:p.changed?"caution":"neutral",children:[p.run1State??"none"," → ",p.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ue,{tone:p.visibilityChanged?"caution":"neutral",children:[p.run1MentionState??"none"," → ",p.run2MentionState??"none"]})})]},p.queryId??p.query??"unknown"))})]})}):null]}):null]})}const ta=20,Vt=50,Sm=50,Cm=50;function ka(t){return t==="viewer"}function Pa(t){return t?.status==="unavailable"}function Ti(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Mi(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 vn(t,s,n){if(t.kind==="all")return s.map(i=>i.id);if(t.kind==="specific")return s.filter(i=>t.propertyIds.includes(i.id)).map(i=>i.id);const a=new Set(t.groupIds),r=new Set(n.filter(i=>a.has(i.id)).flatMap(i=>i.propertyIds));return s.filter(i=>r.has(i.id)).map(i=>i.id)}function km(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(i=>i.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function sa(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 Sr(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Cr(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 Nn(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 ya(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function na(t){return ya(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ja({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[i,o]=l.useState(""),[m,u]=l.useState(!1),h=i.trim().toLocaleLowerCase(),x=h?t.filter(f=>f.label.toLocaleLowerCase().includes(h)):t,c=m?x:x.slice(0,Sm),y=c.length<x.length;function N(){const f=new Set([...s,...c.map(b=>b.id)]);n(t.filter(b=>f.has(b.id)).map(b=>b.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:i,onChange:f=>o(f.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:c.length===0,onClick:N,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]}),x.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 ",c.length," of ",x.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:c.map(f=>{const b=s.includes(f.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${f.label}`,checked:b,type:"checkbox",onChange:p=>n(Ti(s,f.id,p.currentTarget.checked))}),e.jsx("span",{children:f.label})]}),f.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[f.urlCount," URLs"]})]},f.id)})}),y?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>u(!0),children:"Show all Properties"}):null]})]})}function Aa(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ue,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Ra({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function Pm({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[i,o]=l.useState(null),m=t.preview,u=m?.counts.needsAttention??0,h=m?.rows.filter(C=>C.status==="matched")??[],x=m?.rows??[],c=x.filter(C=>C.status!=="matched"),y=Math.max(1,Math.ceil(x.length/Vt)),N=Math.min(s,y-1),f=x.slice(N*Vt,(N+1)*Vt),b=Math.max(1,Math.ceil(c.length/Vt)),p=Math.min(a,b-1),T=c.slice(p*Vt,(p+1)*Vt),_=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,O=h.length>0&&!t.isApplying,$=m!==null&&i===m.previewChecksum,g=c.length>0&&p===b-1;l.useEffect(()=>{n(0),r(0),o(null)},[m?.previewChecksum]);async function v(C){if(C)try{t.onCsvChange(await C.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:C=>{v(C.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:C=>t.onCsvChange(C.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:!_,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),m?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[m.counts.matchedRows," matched · ",m.counts.groupsReady," group",m.counts.groupsReady===1?"":"s"," ready",u>0?` · ${u} need${u===1?"s":""} attention`:""]}),m.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:m.groupChanges.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.label}),e.jsx("td",{className:"text-secondary",children:C.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:C.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[C.addedTargetKeys.length,C.unchangedTargetKeys.length>0?` · ${C.unchangedTargetKeys.length} already members`:""]})]},C.groupKey))})]})}):null,m.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",m.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:f.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:Sr(C.status),children:Cr(C.status)}),Nn(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Nn(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",N+1," of ",y," · ",m.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===0,onClick:()=>n(C=>Math.max(0,C-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===y-1,onClick:()=>n(C=>Math.min(y-1,C+1)),children:"Next 50 rows"})]})]}):null,u>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",u," row",u===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:T.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:Sr(C.status),children:Cr(C.status)}),Nn(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Nn(C)}):null]})]},C.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 ",p+1," of ",b]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>r(C=>Math.max(0,C-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===b-1,onClick:()=>r(C=>Math.min(b-1,C+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:$,disabled:t.isApplying||!g,onChange:C=>o(C.currentTarget.checked?m.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",u," row",u===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!O||!$,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!O,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Creating groups…":`Create ${m.counts.groupsReady} group${m.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const Am="—";function Rm({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:i=!1,isBusy:o=!1,canContinue:m=!0,onSelectedQueryIdsChange:u,onApplySelectedQueries:h,onClearQueryAssignments:x,onRemoveQuery:c,onCreateQueries:y,onCreateAndPairQuestions:N,isCreatingQueries:f=!1,createQueriesError:b=null,onManageProjectQueries:p,groups:T,audience:_,onAudienceChange:O,assignmentImpact:$=null,isPreviewingAssignmentImpact:g=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:C,assignmentNotice:J=null,onReplaceAssignments:z,isReplacingAssignments:P=!1,onBack:k,onContinue:U}){const[M,te]=l.useState(""),[je,le]=l.useState(!1),[Q,de]=l.useState(!1),[oe,G]=l.useState(""),[F,w]=l.useState(""),[Z,re]=l.useState(null);if(Pa(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Ra,{message:s.message})});const ce=ka(t),K=_,xe=O,q=vn(K,n,T),ie=q.length,Se=ie>0&&r.length>0&&!i&&!o&&!g&&$!==null&&v===null,Xe=x??c,rt=M.trim().toLocaleLowerCase(),it=rt?a.filter(I=>na(I).toLocaleLowerCase().includes(rt)):a,Ge=it.filter(I=>(I.propertyIds?.length??0)===0),X=Q?Ge:it,Be=je?X:X.slice(0,Cm),Ve=Be.filter(I=>!ya(I)),Pe=[...new Set(oe.split(`
|
|
5
|
+
`).map(I=>I.trim()).filter(Boolean))],He=[...F.matchAll(/\{([a-z][\w-]*)\}/gi)].map(I=>I[1]),Ce=n.filter(I=>q.includes(I.id)),ve=He.length===0||F.trim()===""?[]:Ce.map(I=>({propertyId:I.id,text:He.reduce((be,De)=>be.replaceAll(`{${De}}`,I.label),F.trim())})),D=[...new Set(ve.map(I=>I.text))];function R(){const I=new Set([...r,...Ve.map(be=>be.id)]);u(a.filter(be=>I.has(be.id)).map(be=>be.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."})]})}),ce?e.jsx(Aa,{}):null,ce?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:K.kind==="all"?"all":K.kind==="specific"?"specific":`group:${K.groupIds[0]??""}`,onChange:I=>{const be=I.currentTarget.value;be==="all"?xe({kind:"all"}):be==="specific"?xe({kind:"specific",propertyIds:[]}):be.startsWith("group:")&&xe({kind:"groups",groupIds:[be.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]}),T.length>0?e.jsx("optgroup",{label:"Groups",children:T.map(I=>{const be=vn({kind:"groups",groupIds:[I.id]},n,T).length;return e.jsx("option",{value:`group:${I.id}`,disabled:be===0,children:sa(I,n)},I.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),K.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:K.groupIds.map(I=>{const be=T.find(De=>De.id===I);return be?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:[sa(be,n),e.jsx("button",{type:"button","aria-label":`Remove ${be.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 De=K.groupIds.filter(H=>H!==be.id);xe(De.length>0?{kind:"groups",groupIds:De}:{kind:"all"})},children:"×"})]},be.id):null})}),T.some(I=>!K.groupIds.includes(I.id)&&vn({kind:"groups",groupIds:[I.id]},n,T).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:I=>{I.currentTarget.value&&xe({kind:"groups",groupIds:[...K.groupIds,I.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"}),T.filter(I=>!K.groupIds.includes(I.id)).map(I=>{const be=vn({kind:"groups",groupIds:[I.id]},n,T).length;return e.jsx("option",{value:I.id,disabled:be===0,children:sa(I,n)},I.id)})]})]}):null,ie===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,K.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ja,{legend:"Specific Properties",properties:n,selectedPropertyIds:K.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:I=>{xe({kind:"specific",propertyIds:I})}})}):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."})]}),ce||!y?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:oe,onChange:I=>G(I.currentTarget.value),placeholder:`best apartments in dallas
|
|
6
|
+
luxury apartments atlanta
|
|
7
|
+
pet friendly apartments austin`}),b?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:b}):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:Pe.length===0||f||o,onClick:()=>{Promise.resolve(y(Pe)).then(()=>G(""),()=>{})},children:f?"Adding…":`Add ${Pe.length||""} ${Pe.length===1?"query":"queries"}`.replace(" "," ")}),p?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o,onClick:p,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:F,onChange:I=>w(I.target.value),placeholder:"apartments near {property}"}),F.trim()===""?null:He.length===0?e.jsxs("p",{className:"mt-2 text-sm text-caution",children:["Add ","{property}"," to the pattern, or use the box above for a single query."]}):Ce.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:[D.length," ",D.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:D.slice(0,3).map(I=>e.jsx("li",{className:"text-sm text-strong",children:I},I))}),D.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",D.length-3," more"]}):null]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:ve.length===0||f||o||!N,onClick:()=>{N&&Promise.resolve(N(ve)).then(()=>w(""),()=>{})},children:f?"Adding…":`Add ${ve.length||""} ${ve.length===1?"query":"queries"}`.replace(" "," ")}),ve.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"," ",ve.length," assignment",ve.length===1?"":"s","."]}):null]})]})]}),ce?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:Ve.length===0,onClick:R,children:"Select all shown queries"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>u([]),children:"Clear query selection"}),e.jsx(A,{type:"button",size:"sm",className:"min-h-11",disabled:!Se,onClick:()=>{h({queryIds:r,propertyIds:q,...K.kind==="groups"?{groupIds:K.groupIds}:{}})},children:i?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${km(K,T,ie)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[g?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,$?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",$.assignmentCount," Property assignment",$.assignmentCount===1?"":"s"," · ",$.addedAssignments," new, ",$.alreadyPresentAssignments," already assigned"," · ",$.fullRunProviderCalls," provider request",$.fullRunProviderCalls===1?"":"s"," per full run"," · ",$.addedProviderCalls," new",K.kind==="groups"?` · ${$.resolvedPropertyCount} unique ${$.resolvedPropertyCount===1?"Property":"Properties"}${$.overlapCount>0?`, ${$.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}),C?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:C,children:"Retry impact"}):null,k?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:k,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ie," Properties = ",r.length*ie," assignments"]})]}),J?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:J}):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:M,onChange:I=>{te(I.currentTarget.value),le(!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 ",Be.length," of ",X.length," queries,"," ",it.length-Ge.length," of ",it.length," applied"]}),ce||Ge.length===0?null:e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{de(I=>!I),le(!1)},children:Q?"Show all queries":`Show the ${Ge.length} not applied`})]})]}):null,Be.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:[ce?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),ce?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:Be.map(I=>{const be=ya(I),De=na(I),H=r.includes(I.id),Ee=(I.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[ce?null:be?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 ${De}`,checked:H,type:"checkbox",onChange:lt=>u(Ti(r,I.id,lt.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:De})}),e.jsx("td",{className:"text-secondary",children:Mi(I.propertyIds??[],n)}),ce?null:e.jsx("td",{className:"text-right",children:Ee?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[z?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o||P,onClick:()=>re({queryId:I.id,propertyIds:[...I.propertyIds??[]]}),"aria-label":`Replace query assignments for ${De}`,children:"Replace assignments"}):null,e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o,onClick:()=>{Xe(I.id)},"aria-label":`Clear query assignments for ${De}`,children:"Clear assignments"})]}):null})]},I.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,ce||!Z?null:(()=>{const I=a.find(H=>H.id===Z.queryId),be=I?na(I):"this query",De=Z.propertyIds.filter(H=>n.some(Ee=>Ee.id===H));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 “",be,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(ja,{legend:"Properties for this query",properties:n,selectedPropertyIds:De,onSelectedPropertyIdsChange:H=>re(Ee=>Ee&&{...Ee,propertyIds:[...H]})})}),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:P||o,onClick:()=>re(null),children:"Keep current assignments"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:De.length===0||P||o||!z,onClick:()=>{z&&Promise.resolve(z({queryId:Z.queryId,propertyIds:De}))},children:P?"Replacing assignments…":`Replace with ${De.length} ${De.length===1?"Property":"Properties"}`})]})]})})(),Be.length<X.length?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>le(!0),children:"Show all queries"}):null,ce?null:e.jsxs(e.Fragment,{children:[m?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${k?"justify-between":"justify-end"}`,children:[k?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",disabled:o,onClick:k,children:"Back"}):null,e.jsx(A,{type:"button",variant:Se?"outline":"default",className:"min-h-11",disabled:!m||o,onClick:U,children:"Continue"})]})]})]})}function $m({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:i=!1,onGroupDraftChange:o,onSaveGroup:m,onEditGroup:u,onRemoveGroup:h,onClearGroupDraft:x,membershipImport:c,onBack:y,onContinue:N}){if(Pa(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Ra,{message:s.message})});const f=ka(t),b=r.name.trim().length>0&&r.propertyIds.length>0&&!i,p=n.filter($=>r.propertyIds.includes($.id)).length,T=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,_=!f&&(u!==void 0||h!==void 0);function O(){if(x){x();return}o({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),f?e.jsx(Aa,{}):null,f||!c?null:e.jsx(Pm,{value:c}),f?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:$=>o({...r,name:$.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:[p," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(ja,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:$=>o({...r,propertyIds:$})})})]}),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:$=>o({...r,competitorDomains:$.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:!b,onClick:()=>{m(r)},children:i?"Saving group…":"Save group"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!T,onClick:O,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."})]}),T?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"}),_?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map($=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:$.name}),e.jsx("td",{className:"text-secondary",children:Mi($.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:$.competitors.length>0?$.competitors.join(", "):"None"}),_?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[u?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${$.name}`,onClick:()=>u($),children:"Edit"}):null,h?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${$.name}`,onClick:()=>{h($.id)},children:"Remove"}):null]})}):null]},$.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,f?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${y?"justify-between":"justify-end"}`,children:[y?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:y,children:"Back"}):null,e.jsx(A,{type:"button",className:"min-h-11",disabled:T,onClick:N,children:a.length===0&&!T?"Continue without groups":"Continue"})]})]})}function Im({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:i,onReviewChanges:o,isReviewing:m=!1,canReviewChanges:u=!0,reviewedChanges:h,reviewChangesError:x,canPublish:c,isPublishing:y=!1,onPublish:N}){const[f,b]=l.useState(ta),[p,T]=l.useState(ta),[_,O]=l.useState(ta);if(Pa(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Ra,{message:s.message})});const $=ka(t),g=r?.items??[],v=r?.coverageItems??[],C=g.slice(0,f),J=v.slice(0,p),z=a.slice(0,_),P=o!==void 0,k=h!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),$?e.jsx(Aa,{}):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,")"]}),g.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:C.map(U=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:U.url}),e.jsx("p",{className:"mt-1 text-secondary",children:U.reason})]},`${U.url}-${U.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",C.length," of ",g.length]}),C.length<g.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>b(U=>U+Vt),children:"Show next 50 URLs"}):null]})]}):null,$?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,")"]}),J.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[J.map(U=>e.jsxs("section",{"aria-label":`${U.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:U.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:U.savedUrls.map(M=>e.jsx("li",{className:"break-all text-secondary",children:M},M))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),U.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:U.currentSitemapUrls.map(M=>e.jsx("li",{className:"break-all text-secondary",children:M},M))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},U.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",J.length," of ",v.length]}),J.length<v.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>T(U=>U+Vt),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??Am})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,h?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((U,M)=>e.jsx("li",{children:U},`${U}-${M}`))}):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:z.map(U=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:U.title}),U.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:U.detail}):null]}),e.jsx(ue,{tone:U.tone??"caution",children:"Needs attention"})]},U.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",z.length," of ",a.length]}),z.length<a.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>O(U=>U+Vt),children:"Show next 50 exceptions"}):null]})]})]}),$?null:e.jsxs(e.Fragment,{children:[P&&x?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:x}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${i?"justify-between":"justify-end"}`,children:[i?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:i,children:"Back"}):null,o!==void 0&&!k?e.jsx(A,{type:"button",className:"min-h-11",disabled:m||!u,onClick:()=>{o()},children:m?"Reviewing changes…":"Review changes"}):e.jsx(A,{type:"button",className:"min-h-11",disabled:!c||y,onClick:()=>{N()},children:y?"Publishing setup…":"Publish setup"})]})]})]})}const Lm={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Tm(t){return t.trim().toLocaleLowerCase()}function Mm(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function Dm({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 Em({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const i=!t||r==="reviewing",o=i||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function m(u,h){n({...s,[u]:h})}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(ue,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:u=>{u.preventDefault(),!o&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:i,onChange:u=>m("sitemapUrl",u.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:i,onChange:u=>m("examplePropertyUrl",u.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:i,onChange:u=>m("preferredHost",u.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:i,onChange:u=>m("propertyPathPattern",u.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:i,onChange:u=>m("additionalHost",u.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:i,onChange:u=>m("additionalPathPattern",u.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:i,onChange:u=>m("excludedPaths",u.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:o,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function qm({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:i,onSelectedPropertyIdsChange:o,onContinue:m,isContinuing:u=!1,onRetryProperties:h,onReturnToImport:x,maxVisibleProperties:c,onShowAllProperties:y}){const N=Tm(a),f=s.filter(z=>Mm(z,N)),b=Math.max(1,c??f.length),p=f.slice(0,b),T=new Set(i),_=s.filter(z=>T.has(z.id)).map(z=>z.id),O=p.length<f.length;function $(z){const P=new Set(z);o(s.filter(k=>P.has(k.id)).map(k=>k.id))}function g(z,P){if(!t||u)return;const k=new Set(_);P?k.add(z):k.delete(z),$(k)}function v(){!t||u||$([..._,...p.map(z=>z.id)])}function C(){!t||u||o([])}function J(){!t||u||_.length===0||m(_)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||u,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:h,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:x,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:u,onChange:z=>r(z.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:u,onClick:v,children:"Select all shown"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:u||_.length===0,onClick:C,children:"Clear selection"})]}):null]}),f.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:x,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 ",p.length," of ",f.length," Properties"]}),e.jsxs("p",{children:[_.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:p.map(z=>{const P=Lm[z.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:z.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(Dm,{property:z})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(ue,{tone:P.tone,children:P.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 ${z.name}`,checked:_.includes(z.id),disabled:u,onChange:k=>g(z.id,k.target.checked),className:"size-6 accent-accent"})})}):null]},z.id)})})]})}),O&&y?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:u,onClick:y,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:u,onClick:x,children:"Back"}),e.jsx(A,{type:"button",disabled:u||_.length===0,onClick:J,children:u?"Saving Properties…":"Continue"})]}):null]}):null]})}function Om(t){return t.activeStep==="import"?e.jsx(Em,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(qm,{...t})}const Fm=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function _m({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:i}){const o=l.useRef(null),m=l.useRef(null),u=l.useRef(null),h=l.useRef(null),x=l.useRef(!1),[c,y]=l.useState(!1);return l.useEffect(()=>{s||y(!1)},[s]),l.useEffect(()=>{const N=x.current;x.current=c,c?u.current?.focus():N&&h.current?.focus()},[c]),l.useEffect(()=>{const N=o.current;if(o.current=t,N===null||N===t)return;const f=m.current?.querySelector('h1, h2, h3, [role="heading"]');f&&(f.tabIndex=-1,f.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(ue,{tone:"caution",children:"Unpublished changes"}),n&&a?c?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:u,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>y(!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:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>y(!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:Fm.map(N=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===N.id?"step":void 0,onClick:()=>r(N.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===N.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:N.label}):e.jsx("span",{"aria-current":t===N.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===N.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:N.label})},N.id))})}),e.jsx("div",{ref:m,children:i})]})}function Um(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Om,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Rm,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx($m,{...t.groups,access:s}):"review"in t?e.jsx(Im,{...t.review,access:s}):null}function wn(t){return e.jsx(_m,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Um(t)})}function Di(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function ft(t){return{"If-Match":t,"Idempotency-Key":Di()}}function cs(t){return t instanceof Ls&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function Rt(t,s){return t instanceof Ls?s:(t instanceof Error?t.message.trim():"")||s}function Gm(t){const s="Could not calculate assignment impact.";if(!(t instanceof Ls)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Bm={loadSetup:t=>Qe(()=>Fo({client:V,path:{name:t}})),loadDraft:t=>Qe(()=>Oo({client:V,path:{name:t}})),createDraft:(t,s)=>Qe(()=>qo({client:V,path:{name:t},headers:{"Idempotency-Key":Di()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>Qe(()=>Eo({client:V,path:{name:t},headers:ft(s),body:n})),applySitemapSelection:(t,s,n,a)=>Qe(()=>Do({client:V,path:{name:t},headers:ft(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>Qe(()=>Mo({client:V,path:{name:t},body:s})),applyAssignments:(t,s,n)=>Qe(()=>To({client:V,path:{name:t},headers:ft(s),body:n})),replaceAssignments:(t,s,n)=>Qe(()=>Lo({client:V,path:{name:t},headers:ft(s),body:n})),applyPairedAssignments:(t,s,n)=>Qe(()=>Io({client:V,path:{name:t},headers:ft(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>Qe(()=>$o({client:V,path:{name:t},headers:ft(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>Qe(()=>Ro({client:V,path:{name:t},headers:ft(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>Qe(()=>Ao({client:V,path:{name:t},headers:ft(s),body:{target:n}})),upsertGroup:(t,s,n)=>Qe(()=>Po({client:V,path:{name:t},headers:ft(s),body:{group:n}})),removeGroup:(t,s,n)=>Qe(()=>ko({client:V,path:{name:t},headers:ft(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>Qe(()=>Co({client:V,path:{name:t},headers:ft(s),body:n})),removeCompetitor:(t,s,n,a)=>Qe(()=>So({client:V,path:{name:t},headers:ft(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>Qe(()=>wo({client:V,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>Qe(()=>No({client:V,path:{name:t},headers:ft(s),body:n})),compilePreview:t=>Qe(()=>vo({client:V,path:{name:t}})),diffPreview:t=>Qe(()=>jo({client:V,path:{name:t}})),publish:(t,s,n)=>Qe(()=>yo({client:V,path:{name:t},headers:ft(s),body:n})),discard:(t,s)=>Qe(()=>bo({client:V,path:{name:t},headers:ft(s)}))},kr={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},Ks={name:"",propertyIds:[],competitorDomains:""},Pr=50;function Qs(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Km(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 Ar(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(o=>o==="*"||o==="{slug}").length!==1||r.some(o=>o.includes("*")&&o!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(o=>o==="*"?"{slug}":o).join("/")}`}const n=t.examplePropertyUrl.trim();if(!n)throw new Error("Add one example Property page so Canonry can identify the matching URLs.");try{const a=new URL(n).pathname.split("/").filter(Boolean);if(a.length===0)throw new Error;return a[a.length-1]="{slug}",`/${a.join("/")}`}catch{throw new Error("Example Property page must be a valid web address.")}}function Vm(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const o=r.split("/").filter(Boolean).at(-1)??r,m=o.startsWith("*"),u=o.endsWith("*"),h=o.slice(m?1:0,u?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const x=m&&u?"contains":m?"suffix":u?"prefix":"exact",c=`${x}:${h}`;n.has(c)||(n.add(c),s.push({kind:x,value:h}))}return s}function zm(t){const s=Km(t.sitemapUrl),n=t.examplePropertyUrl.trim()?Qs(t.examplePropertyUrl):null,a=Qs(t.preferredHost)??n??Qs(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=Qs(t.additionalHost),i=t.additionalHost.trim().length>0,o=t.additionalPathPattern.trim().length>0;if(i!==o||i&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const m=Vm(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:Ar(t)},...r?{aliases:[{host:r,pathTemplate:Ar({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...m.length>0?{excludedSlugPatterns:m}:{}}}}function Qm(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 Hm(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 Rr(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Wm(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function aa(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function va(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function $r(t){return Qs(t)}function Ei(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 qi(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 Oi(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Fi(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function Ym(t,s){const n=Ei(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const i=n.urlMatchers[r];return i?`${n.label} — ${i}`:n.label}if(a==="aliases"&&typeof r=="number"){const i=n.aliases[r];return i?`${n.label} — ${i}`:n.label}return n.label}function Xm(t,s){const n=qi(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const i=n.competitors.at(r)?.domain;return i?`${n.label} — ${i}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const i=Fi(t.authoring,n.targetKeys[r]);return`${n.label} — ${i}`}return n.label}function Jm(t,s){const n=Oi(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Fi(t.authoring,n.targetKey)} — ${a}`}function Zm(t,s){return s.path[0]==="identities"?"Project domain":Ym(t,s)??Xm(t,s)??Jm(t,s)}function Ir(t,s,n){const a=Oi(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},i=s.path.at(-1);if(n==="models"&&typeof i=="string")return r.models?.[i];if(n==="locations"&&typeof i=="number")return r.locations?.[i]}function eh(t,s){const n=Zm(s,t);switch(t.ruleId){case"invalid-project-identity":return{title:"Fix the project domain",detail:"The project domain is not valid. Update it in project settings, then review again.",tone:"negative",affected:n};case"target-limit-exceeded":return{title:"Reduce Properties",detail:"This setup exceeds the Properties publishing limit. Remove some Properties, then review again.",tone:"negative"};case"duplicate-target-key":return{title:"Resolve duplicate Properties",detail:"Two Properties use the same setup identifier. Rename or recreate one, then review again.",tone:"negative",affected:n};case"no-included-targets":return{title:"Include a Property",detail:"Include at least one Property before publishing.",tone:"negative"};case"target-url-matcher-invalid":return{title:"Fix a Property URL",detail:"Use a valid web address, site-wide address, or URL pattern for this Property.",tone:"negative",affected:n};case"target-url-matcher-unowned":return{title:"Use a project domain",detail:"This Property URL must use the project domain or one of its subdomains.",tone:"negative",affected:n};case"target-url-matcher-ambiguous":return{title:"Separate Property URL coverage",detail:"This URL is assigned to more than one Property at the same specificity. Update one of the URLs.",tone:"negative",affected:n};case"target-alias-ambiguous":return{title:"Use distinct Property names",detail:"This name or alias matches another Property. Make each Property name and alias distinct.",tone:"negative",affected:n};case"execution-context-no-provider":return{title:"Choose a provider",detail:"Choose at least one provider before publishing.",tone:"negative",affected:n};case"invalid-provider-model":return{title:"Fix provider settings",detail:"Choose the provider that runs this model, or remove the model setting.",tone:"negative",affected:[n,Ir(s,t,"models")].filter(Boolean).join(" — ")||void 0};case"invalid-location":return{title:"Fix a location",detail:"Choose a location configured for this project, or remove it from the query.",tone:"negative",affected:[n,Ir(s,t,"locations")].filter(Boolean).join(" — ")||void 0};case"target-without-aliases":return{title:"Add Property aliases",detail:"Add a name or alias to measure mentions.",tone:"caution",affected:n};case"duplicate-group-key":return{title:"Resolve duplicate groups",detail:"Two groups use the same setup identifier. Rename one group, then review again.",tone:"negative",affected:n};case"group-unknown-target":return{title:"Fix group Properties",detail:"This group contains a Property that is no longer in setup. Remove it or add the Property back.",tone:"negative",affected:n};case"group-excluded-target":return{title:"Include or remove a grouped Property",detail:"This group contains an excluded Property. Include it or remove it from the group.",tone:"negative",affected:n};case"competitor-invalid-domain":return{title:"Fix a competitor domain",detail:"Enter a valid competitor domain.",tone:"negative",affected:n};case"competitor-matches-project":return{title:"Remove a project domain",detail:"A competitor cannot use the project domain.",tone:"negative",affected:n};case"competitor-duplicate":return{title:"Remove a duplicate competitor",detail:"List each competitor domain only once in a group.",tone:"negative",affected:n};case"duplicate-assignment":return{title:"Remove a duplicate query",detail:"Assign each query to a Property only once.",tone:"negative",affected:n};case"assignment-unknown-target":return{title:"Fix a query assignment",detail:"This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.",tone:"negative",affected:n};case"assignment-excluded-target":return{title:"Include or unassign a Property",detail:"This query is assigned to an excluded Property. Include it or remove the assignment.",tone:"negative",affected:n};case"assignment-unknown-query":return{title:"Remove an unavailable query",detail:"This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.",tone:"negative",affected:n};case"assignment-unclassified":return{title:"Classify a query",detail:"Choose Branded or Non-brand for this query before publishing.",tone:"negative",affected:n};case"query-limit-exceeded":return{title:"Reduce queries",detail:"This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.",tone:"negative"};case"target-without-assignments":return{title:"Assign queries",detail:"Assign at least one query to measure a Property.",tone:"caution",affected:n};case"invalid-compiled-plan":return{title:"Fix setup details",detail:"A setup value could not be validated. Review the affected item, then review again.",tone:"negative",affected:n};case"compiled-plan-too-large":return{title:"Reduce setup size",detail:"This setup is too large to publish. Remove Properties, queries, or groups, then review again.",tone:"negative"};case"active-revision-schema-v1":return{title:"Historical results will be kept",detail:"Existing results remain visible after you publish this setup.",tone:"neutral"}}return{title:t.severity==="fail"?"An unexpected setup issue blocks publishing":"An unexpected setup issue needs review",detail:t.severity==="fail"?"Review the affected item, make a correction, and review again. If it remains blocked, contact support.":"Review the affected item before publishing. If it remains, contact support.",tone:t.severity==="fail"?"negative":"caution",affected:n}}function Sn(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function _i(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 th(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Sn(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Sn(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Sn(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Sn(n,"item")} need review.`:s}})()}${_i(a)}`}function sh(t,s){const n=new Map;for(const a of t){const r=eh(a,s),i=[a.ruleId,a.severity,r.title,r.detail].join("\0"),o=n.get(i)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};o.paths.add(JSON.stringify(a.path)),r.affected&&o.affected.add(r.affected),n.set(i,o)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:th(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function ra(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function ia(t,s,n){const a=Ei(n,t.path),r=qi(n,t.path),i=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,o=i?n?.targets.find(x=>x.stableKey===i):void 0,m=a?.label??r?.label,u=_i(m?[m]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${u}`};case"excluded-target-has-assignments":return{...h,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${u}`};case"group-unknown-target":return{...h,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${u}`};case"measurement.discovery.proposed_new_target":{const x=ra(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${x}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const x=ra(a)??"the proposed Property",c=o?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${x}. It may be the same Property as ${c}.`}}case"measurement.discovery.rebind_ambiguous":{const x=ra(a)??"the proposed Property",c=o?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${x}. It may match ${c}; choose the correct Property.`}}default:return{...h,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function nh(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,i=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),i>0&&n.push(`${i} query assignment ${i===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 qt(t){return[...new Set(t)]}function ns(t){return qt(t).sort()}function ah(t,s,n){return t.kind==="groups"?{groupKeys:ns(t.groupIds),queryIds:ns(n)}:{targetKeys:ns(t.kind==="all"?s:t.propertyIds),queryIds:ns(n)}}function rh(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 Lr(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function ih(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(Lr).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(Lr).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:va(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function lh({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:i,canEdit:o=!0,onCreateQueries:m,onManageProjectQueries:u,onPublished:h,service:x=Bm}){const[c,y]=l.useState(null),[N,f]=l.useState(null),[b,p]=l.useState("import"),[T,_]=l.useState(!0),[O,$]=l.useState(null),[g,v]=l.useState(null),[C,J]=l.useState([]),[z,P]=l.useState({...kr}),[k,U]=l.useState("idle"),[M,te]=l.useState(""),[je,le]=l.useState(Pr),[Q,de]=l.useState([]),[oe,G]=l.useState([]),[F,w]=l.useState({kind:"all"}),[Z,re]=l.useState(null),[ce,K]=l.useState(null),[xe,q]=l.useState(!1),[ie,Se]=l.useState(null),[Xe,rt]=l.useState(0),[it,Ge]=l.useState(null),[X,Be]=l.useState({...Ks}),[Ve,Pe]=l.useState(null),[He,Ce]=l.useState(""),[ve,D]=l.useState(null),[R,I]=l.useState(!1),[be,De]=l.useState(!1),[H,Ee]=l.useState(null),[lt,bt]=l.useState(null),[ke,Oe]=l.useState(null),[ht,Ue]=l.useState(null),[We,Ae]=l.useState(null),jt=l.useRef(0),Ct=l.useRef(0),Le=N?.draft??null,Te=N?.etag??null,ot=l.useMemo(()=>!o&&i?{baseActiveRevision:i.revision,authoring:ih(i)}:null,[o,i]),Fe=Le??ot;async function Tt(S){const B=++jt.current;_(!0),$(null);try{let[pe,ee]=await Promise.all([x.loadSetup(t),x.loadDraft(t)]);if(!ee.draft&&S&&o&&(await x.createDraft(t,pe.activeRevision),[pe,ee]=await Promise.all([x.loadSetup(t),x.loadDraft(t)])),B!==jt.current)return;y(pe),f(ee),p(Qm(ee.draft));const se=aa(ee.draft);de(se)}catch(pe){if(B!==jt.current)return;$(Rt(pe,"Could not load advanced measurement setup."))}finally{B===jt.current&&_(!1)}}l.useEffect(()=>(Tt(!0),()=>{jt.current+=1}),[t,o,x]),l.useEffect(()=>{!T&&!Le&&ot&&p("properties")},[Le,T,ot]);async function vt(){const S=await x.loadDraft(t);return f(S),S}async function pt(S){Ae(null);try{const[B,pe]=await Promise.all([x.loadSetup(t),x.loadDraft(t)]);y(B),f(pe);const ee=aa(pe.draft);de(ee),p(se=>Hm(pe.draft,se)),v(S)}catch(B){v(Rt(B,S))}}async function Je(S,B,pe,ee={}){const{preserveBusyAction:se=!1}=ee;if(!o||!Te||ke&&!se)return null;se||Oe(S),v(null),Ae(null);try{const Re=await B(Te),Wt=await vt();return J((Re.warnings??[]).map((xt,Fs)=>ia(xt,Fs,Wt.draft?.authoring))),Wt}catch(Re){return cs(Re)?await pt("This setup changed in another session. The latest draft is loaded; review your changes again."):v(Rt(Re,pe)),null}finally{se||Oe(null)}}const E=l.useMemo(()=>(Fe?.authoring.targets??[]).map(S=>{const B=Rr(S);return{id:S.stableKey,name:S.label,url:B[0]??"No URL",urls:B,state:Wm(S.status)}}),[Fe]),Ne=l.useMemo(()=>Fe?.authoring.targets.filter(S=>S.status==="included")??[],[Fe]),me=l.useMemo(()=>Ne.map(S=>({id:S.stableKey,label:S.label,urlCount:Rr(S).length})),[Ne]),fe=Fe?.authoring.assignments.length??0,kt=l.useMemo(()=>{if(!Fe)return[];const S=new Set(s.map(ee=>ee.id)),B=s.map(ee=>({id:ee.id,text:ee.query,source:"saved-project-queries",propertyIds:qt(Fe.authoring.assignments.filter(se=>se.queryId===ee.id).map(se=>se.targetKey))})),pe=qt(Fe.authoring.assignments.map(ee=>ee.queryId).filter(ee=>!S.has(ee))).map(ee=>({id:ee,source:"unavailable-tracked-query",state:"missing",propertyIds:qt(Fe.authoring.assignments.filter(se=>se.queryId===ee).map(se=>se.targetKey))}));return[...B,...pe]},[s,Fe]),Mt=l.useMemo(()=>(Fe?.authoring.groups??[]).map(S=>({id:S.stableKey,name:S.label,propertyIds:S.targetKeys,competitors:S.competitors.map(B=>B.domain)})),[Fe]),tt=l.useMemo(()=>{if(oe.length===0)return null;const S=ah(F,me.map(pe=>pe.id),oe);return(S.groupKeys?.length??S.targetKeys?.length??0)>0?S:null},[F,me,oe]),Pt=tt?JSON.stringify(tt):"";l.useEffect(()=>{const S=tt,B=++Ct.current;if(!o||!Le||!Te||!S){re(null),K(null),Se(null),q(!1);return}re(null),K(null),Se(null),q(!0);const pe=window.setTimeout(()=>{x.previewAssignments(t,S).then(ee=>{if(B===Ct.current){if(ee.draftEtag!==Te){re(null),K(null),Se("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}re(ee),K(Pt)}}).catch(ee=>{B===Ct.current&&(re(null),K(null),Se(Gm(ee)))}).finally(()=>{B===Ct.current&&q(!1)})},250);return()=>{window.clearTimeout(pe),Ct.current+=1}},[tt,Pt,Xe,o,Le,Te,t,x]);const is=l.useMemo(()=>[...fe===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...Fe?.authoring.assignments.some(S=>S.queryClass==="unclassified")&&!(ot&&i?.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"}]:[],...C],[fe,ot,i,C,Fe]),Ds=n?{status:"unavailable",message:"Tracked queries are loading."}:a?{status:"unavailable",message:"Tracked queries could not be loaded. Retry before assigning Properties."}:{status:"available"};async function Dt(S){let B;try{B=zm(S)}catch(ee){v(Rt(ee,"Check the sitemap details and try again."));return}P(S),U("reviewing");const pe=await Je("import",ee=>x.importSitemap(t,ee,B),"Could not review this sitemap.");if(pe?.draft){const ee=pe.draft.authoring.targets.filter(Re=>Re.status==="proposed").map(Re=>Re.stableKey),se=pe.draft.authoring.targets.filter(Re=>Re.status==="included").map(Re=>Re.stableKey);de([...se,...ee]),te(""),le(Pr),p("properties"),U("idle")}else U("error")}async function Es(S){if(!m||S.length===0||ke)return[];Oe("create-queries"),Ue(null);try{return await m(S)}catch(B){throw Ue(Za(B)),B}finally{Oe(null)}}async function Ze(S){if(!Le||!Te||ke)return;const B=new Set(S),ee=Le.authoring.targets.filter(Re=>Re.status==="proposed"&&Re.discoveryIdentity).map(Re=>({discoveryIdentity:Re.discoveryIdentity,action:B.has(Re.stableKey)?"create":"ignore"})),se=ee.length>0||Le.authoring.targets.some(Re=>Re.status!=="proposed"&&Re.status==="included"!==B.has(Re.stableKey));Oe("properties"),v(null),Ae(null);try{if(!se){de([...B]),w({kind:"all"}),p("groups");return}await x.applySitemapSelection(t,Te,ee,[...B]);const Re=await vt(),Wt=aa(Re.draft);de(Wt),w({kind:"all"}),p("groups")}catch(Re){cs(Re)?await pt("This setup changed in another session. The latest Properties are loaded."):v(Rt(Re,"Could not save the selected Properties."))}finally{Oe(null)}}async function qs(S){const B=S.groupIds&&S.groupIds.length>0?{groupKeys:ns(S.groupIds),queryIds:ns(S.queryIds)}:{targetKeys:ns(S.propertyIds),queryIds:ns(S.queryIds)};if(!Z||ce!==JSON.stringify(B)||!Te||Z.draftEtag!==Te){v("Review the latest assignment impact before assigning queries.");return}await Je("assignments",ee=>x.applyAssignments(t,ee,B),"Could not apply these queries.")&&(G([]),Ge(`${Z.assignments.added} new assignment${Z.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function Nt(S){if(S.propertyIds.length===0)return;await Je("replace-assignments",pe=>x.replaceAssignments(t,pe,{targetKeys:qt(S.propertyIds),queryIds:[S.queryId]}),"Could not replace this query assignment.")&&(G(pe=>pe.filter(ee=>ee!==S.queryId)),Ge("Query assignments replaced."))}async function Os(S,B=!1){if(S.length===0)return;if(!await Je("paired-assignments",ee=>x.applyPairedAssignments(t,ee,[...S]),"Could not assign these queries.",{preserveBusyAction:B}))throw new Error("Could not assign these queries.")}async function Qt(S){if(!(!o||!m||S.length===0||ke)){Oe("create-and-pair-questions"),Ue(null);try{let B;try{B=await m(qt(S.map(se=>se.text)))}catch(se){throw Ue(Za(se)),se}const pe=new Map(B.map(se=>[se.query,se.id])),ee=S.map(se=>({targetKey:se.propertyId,queryId:pe.get(se.text)})).filter(se=>se.queryId!==void 0);if(ee.length!==S.length){const se=new Error("The created queries could not be matched to their Properties.");throw Ue("The queries were added, but could not be paired with every Property. Try again to pair them."),se}try{await Os(ee,!0)}catch(se){throw Ue("The queries were added, but could not be assigned to their Properties. Try again to pair them."),se}}finally{Oe(null)}}}async function ys(S){if(!Le)return;const B=qt(Le.authoring.assignments.filter(ee=>ee.queryId===S).map(ee=>ee.targetKey));if(B.length===0)return;await Je(`remove-${S}`,ee=>x.removeAssignment(t,ee,B,S),"Could not clear this query assignment.")&&G(ee=>ee.filter(se=>se!==S))}async function ls(S){if(!Le||!Te||ke)return;const B=S.name.trim();if(!B)return;const pe=Ve??va(B,"group"),ee=Le.authoring.groups.find(xt=>xt.stableKey===pe);if(ee&&Ve===null){v(`A group named "${ee.label}" already exists. Edit it or choose a different name.`);return}const se=S.competitorDomains.split(/[\s,]+/).map(xt=>xt.trim()).filter(Boolean),Re=se.find(xt=>$r(xt)===null);if(Re){v(`"${Re}" is not a valid competitor domain.`);return}const Wt=qt(se.map(xt=>$r(xt)));Oe("group"),v(null),Ae(null);try{const xt=await x.upsertGroup(t,Te,{stableKey:pe,label:B,targetKeys:qt(S.propertyIds),competitors:Wt.map(At=>ee?.competitors.find(Yt=>Yt.domain===At)??{stableKey:va(At,"competitor"),label:At,domain:At,aliases:[]})}),Fs=await vt();J(xt.warnings.map((At,Yt)=>ia(At,Yt,Fs.draft?.authoring))),Be({...Ks}),Pe(null)}catch(xt){cs(xt)?await pt("This setup changed in another session. The latest groups are loaded."):v(Rt(xt,"Could not save this group."))}finally{Oe(null)}}function Ye(S){const B=Le?.authoring.groups.find(pe=>pe.stableKey===S);B&&(Pe(S),Be({name:B.label,propertyIds:[...B.targetKeys],competitorDomains:B.competitors.map(pe=>pe.domain).join(", ")}))}async function js(S){await Je("remove-group",pe=>x.removeGroup(t,pe,S),"Could not remove this group.")&&(w(pe=>pe.kind==="groups"&&pe.groupIds.includes(S)?{kind:"all"}:pe),Ve===S&&(Pe(null),Be({...Ks})))}function Et(S){Ce(S),D(null),Ee(null),bt(null)}async function yt(){if(!(!o||!He.trim()||R||be)){I(!0),Ee(null),bt(null);try{D(await x.previewGroupMembership(t,{csv:He}))}catch(S){D(null),Ee(Rt(S,"Could not review this CSV."))}finally{I(!1)}}}async function vs(S){if(!(!o||!Te||!ve||S.length===0||ke)){if(ve.draftEtag!==Te){Ee("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}De(!0),Oe("group-import"),Ee(null),bt(null),Ae(null);try{const B=await x.applyGroupMembership(t,Te,{csv:He,sourceChecksum:ve.sourceChecksum,previewChecksum:ve.previewChecksum,acceptedRows:qt(S.map(String)).map(Number)}),pe=await vt();J(B.warnings.map((ee,se)=>ia(ee,se,pe.draft?.authoring))),Ce(""),D(null),bt(`${B.addedMemberships} membership${B.addedMemberships===1?"":"s"} added${B.unchangedMemberships>0?`; ${B.unchangedMemberships} already present`:""}.`)}catch(B){cs(B)?(await pt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Ee("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Ee(Rt(B,"Could not apply this CSV."))}finally{Oe(null),De(!1)}}}async function st(){if(!(!Le||!Te||ke||fe===0)){Oe("review"),v(null),Ae(null);try{const[S,B]=await Promise.all([x.compilePreview(t),x.diffPreview(t)]),pe=[...S.checks,...B.checks],ee=pe.some(se=>se.ruleId==="active-revision-schema-v1");if(J(sh(pe.filter(se=>se.ruleId!=="active-revision-schema-v1"),{authoring:Fe?.authoring,queries:s})),!S.ok||!B.ok)return;if(B.diff.activeRevision!==Le.baseActiveRevision){await pt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(S.compiledChecksum!==B.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}Ae({etag:Te,baseActiveRevision:Le.baseActiveRevision,compiledChecksum:S.compiledChecksum,changes:nh(B.diff,ee),providerCalls:S.plan.executionNodes.reduce((se,Re)=>se+Re.expectedSnapshots,0)})}catch(S){v(Rt(S,"Could not review this setup."))}finally{Oe(null)}}}async function Ht(){if(!(!Le||!Te||!We||ke)){if(Te!==We.etag||Le.baseActiveRevision!==We.baseActiveRevision){Ae(null),v("The setup changed after review. Review the latest changes before publishing.");return}Oe("publish"),v(null);try{await x.publish(t,Te,{expectedActiveRevision:We.baseActiveRevision,expectedCompiledChecksum:We.compiledChecksum}),f({draft:null,etag:null}),Ae(null),h?.()}catch(S){cs(S)?await pt("The setup changed before it could be published. Review the latest draft and publish again."):v(Rt(S,"Could not publish this setup."))}finally{Oe(null)}}}async function j(){if(!(!Te||ke)){Oe("discard"),v(null);try{await x.discard(t,Te),f({draft:null,etag:null}),Ae(null),h?.()}catch(S){cs(S)?await pt("This setup changed in another session. The latest draft is loaded."):v(Rt(S,"Could not discard these changes."))}finally{Oe(null)}}}async function ge(){if(!(!Le||!Te||!c||ke)){Oe("restart"),v(null),Ae(null);try{await x.discard(t,Te),await x.createDraft(t,c.activeRevision),P({...kr}),te(""),de([]),G([]),w({kind:"all"}),re(null),Se(null),Ge(null),Be({...Ks}),Pe(null),Ce(""),D(null),Ee(null),bt(null),await Tt(!1)}catch(S){cs(S)?await pt("The setup changed again. Reloaded the latest draft and published setup."):v(Rt(S,"Could not restart this setup."))}finally{Oe(null)}}}if(T)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(O)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:O}),e.jsx(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Tt(!0)},children:"Try again"})]})]});if(!Fe||o&&!Te)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-empty-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-empty-title",children:"Advanced measurement setup"})}),e.jsx("p",{className:"text-sm text-secondary",children:o?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(o&&Le&&c&&Le.baseActiveRevision!==c.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:ke==="restart",onClick:()=>{ge()},children:ke==="restart"?"Restarting…":"Discard draft and restart"})]}),g?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:g}):null]});const ye=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:[c?.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,g?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:g}):null,ye,b==="import"||b==="properties"?e.jsx(wn,{currentStep:b,hasDraft:Le!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{j()},importProperties:{importDraft:z,onImportDraftChange:S=>{P(S),U("idle"),v(null)},onReviewSitemap:S=>{Dt(S)},reviewState:k,properties:E,propertiesState:"ready",propertiesSearch:M,onPropertiesSearchChange:te,maxVisibleProperties:je,onShowAllProperties:()=>le(E.length),selectedPropertyIds:Q,onSelectedPropertyIdsChange:S=>de([...S]),onContinue:S=>{Ze(S)},isContinuing:ke==="properties",onRetryProperties:()=>{vt()},onReturnToImport:()=>p("import")}}):b==="queries"?e.jsx(wn,{currentStep:"queries",hasDraft:Le!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{j()},onManageProjectQueries:u,queries:{onCreateQueries:m?S=>Es(S):void 0,isCreatingQueries:ke==="create-queries"||ke==="create-and-pair-questions",isBusy:ke!==null,createQueriesError:ht,availability:Ds,properties:me,queries:kt,selectedQueryIds:oe,isApplying:ke==="assignments"||ke==="paired-assignments",onSelectedQueryIdsChange:S=>G([...S]),onApplySelectedQueries:S=>qs(S),groups:Mt,audience:F,onAudienceChange:S=>{w(S),Ge(null)},assignmentImpact:Z&&ce===Pt?rh(Z):null,isPreviewingAssignmentImpact:xe,assignmentImpactError:ie,onRetryAssignmentImpact:()=>rt(S=>S+1),assignmentNotice:it,onReplaceAssignments:Nt,isReplacingAssignments:ke==="replace-assignments",onCreateAndPairQuestions:o&&m?Qt:void 0,onClearQueryAssignments:ys,onRemoveQuery:ys,canContinue:fe>0,onBack:()=>p("groups"),onContinue:()=>p("review")}}):b==="groups"?e.jsx(wn,{currentStep:"groups",hasDraft:Le!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{j()},groups:{properties:me,groups:Mt,groupDraft:X,isSaving:ke==="group",onGroupDraftChange:Be,onSaveGroup:ls,onEditGroup:S=>Ye(S.id),onRemoveGroup:js,onClearGroupDraft:()=>{Pe(null),Be({...Ks})},membershipImport:{csv:He,preview:ve,isReviewing:R,isApplying:be,error:H,notice:lt,onCsvChange:Et,onReview:yt,onApply:vs},onBack:()=>{p("properties")},onContinue:()=>p("queries")}}):e.jsx(wn,{currentStep:"review",hasDraft:Le!==null,canEdit:o,onStepChange:o?void 0:p,onDiscard:()=>{j()},review:{counts:{properties:Ne.length,queries:new Set(Fe.authoring.assignments.map(S=>S.queryId)).size,groups:Fe.authoring.groups.length,assignments:Fe.authoring.assignments.length,providerCalls:We?.providerCalls},flaggedExceptions:is,reviewedChanges:We?.changes,isReviewing:ke==="review",canReviewChanges:fe>0&&!ke,onReviewChanges:st,onBack:()=>p("queries"),canPublish:We!==null&&!ke,isPublishing:ke==="publish",onPublish:Ht}})]})}const oh=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Tr(t){return t.label!=="Complete"}const ds="__all_properties__",ch=50,Ui=50,dh=20,uh=50,mh=250,hh=5,xh=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],ph={"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"},Gi={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."},gh={numerator:null,denominator:null,reason:"plan_v1"};function Xs(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 fh(t){return Xs(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function Bi(t){if(Xs(t))return"";const s=t.reason??"unavailable";return Gi[s]??s}function Mr(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 bh(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function yh(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function jh(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function Hs({metric:t,compact:s=!1}){const n=s?Xs(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Xs(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",...Xs(t)?{}:{title:Bi(t)},children:e.jsx("span",{className:n,children:fh(t)})})}function $a({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 Dr({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,i]=l.useState(Ui),o=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:o.map((m,u)=>e.jsx("li",{className:a,children:m},`${m}:${u}`))}),e.jsx($a,{shown:o.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>i(Number.MAX_SAFE_INTEGER)})]})]})}function vh({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(Ui),i=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:i.map(o=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(ue,{tone:o.tone,children:ph[o.kind]}),o.historical?e.jsx(ue,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:o.query}),o.provider||o.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[o.provider,o.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:o.url})]},o.id))})]})}),e.jsx($a,{shown:i.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Nh({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Dr,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Dr,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(vh,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function wh({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(Hs,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Er({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function i(o){if(r)return;const m=n.findIndex(x=>x.value===s);let u=null;if(o.key==="ArrowRight"||o.key==="ArrowDown"?u=(m+1)%n.length:o.key==="ArrowLeft"||o.key==="ArrowUp"?u=(m-1+n.length)%n.length:o.key==="Home"?u=0:o.key==="End"&&(u=n.length-1),u===null)return;o.preventDefault();const h=n[u];a(h.value),o.currentTarget.querySelectorAll('[role="radio"]')[u].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:i,children:n.map(o=>{const m=o.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":m,tabIndex:m?0:-1,disabled:r,onClick:()=>a(o.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${m?"segmented-option-active":""}`,children:o.label},o.value)})})}function Sh({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 Ch({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:i=!1,isViewLoading:o=!1,isLoadingMore:m=!1,isLoadMoreError:u=!1,viewSearch:h,onViewChange:x,onLoadMore:c,onPropertyExpand:y,onRetryEvidence:N,renderPropertyLink:f}){const b=t.currentView!=null,p=t.classReporting==="available"&&(b||t.classScopes!=null),[T,_]=l.useState(t.currentView?.queryClass??"all"),[O,$]=l.useState(t.currentView?.scope.key??ds),[g,v]=l.useState(h??""),[C,J]=l.useState(ch),[z,P]=l.useState(dh),[k,U]=l.useState(t.currentView?.sort??"label-asc"),[M,te]=l.useState(null),je=l.useRef(h??""),le=p&&!b&&T!=="all"?T==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,Q=b?{aggregate:t.currentView.aggregate,groups:[]}:le,de=l.useCallback(D=>{if(!b||!x)return;const R=D.scope??(O===ds?"all":"group"),I=D.search??g;je.current=I,x({scope:R,...R==="group"?{groupKey:D.groupKey??O}:{},queryClass:D.queryClass??T,...I?{search:I}:{},...D.sort?{sort:D.sort}:{}})},[x,g,T,O,b]);l.useEffect(()=>{!t.currentView||o||(_(t.currentView.queryClass),$(t.currentView.scope.key??ds),t.currentView.sort&&U(t.currentView.sort))},[o,t.currentView]),l.useEffect(()=>{h!==void 0&&(je.current=h,v(D=>D.trim()===h.trim()?D:h))},[h]),l.useEffect(()=>{if(!b||!x||g===je.current)return;const D=window.setTimeout(()=>de({search:g}),mh);return()=>window.clearTimeout(D)},[x,de,g,b]);const oe=t.availableGroups??Q.groups;l.useEffect(()=>{O===ds||oe.some(D=>D.id===O)||$(ds)},[oe,O]);const G=b?void 0:Q.groups.find(D=>D.id===O),F=G?.aggregate??Q.aggregate,w=D=>p?D:gh,Z=k,re=g.trim().toLocaleLowerCase(),ce=l.useMemo(()=>!b&&re?F.properties.filter(D=>D.name.toLocaleLowerCase().includes(re)):F.properties,[F.properties,re,b]),K=b?ce:ce.slice(0,C),xe=(b?t.currentView?.scope.kind==="group":G!=null)&&T==="non-brand"&&p&&(b||G.confirmedCompetitorCount>0)&&(F.shareOfVoice?.length??0)>0,q=p?F.unavailablePropertyCount??0:0,ie=t.flaggedResults.reduce((D,R)=>D+(R.count??1),0),Se=t.flaggedResultsTotal??ie,Xe=[w(F.metrics.propertiesMentioned),w(F.metrics.mentionCoverage),w(F.metrics.citationCoverage)].map(Bi).find(Boolean),rt=p?t.nextActionText??Xe??(q>0?`${q} ${q===1?"property is":"properties are"} unavailable.`:Se>0?`${Se} flagged ${Se===1?"result needs":"results need"} review.`:null):Gi.plan_v1,X=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?bh(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,Be=yh(t.latestMeasurement.date),Ve=[{value:ds,label:"All properties"},...oe.map(D=>({value:D.id,label:D.label}))],Pe=oe.length>hh;function He(D){$(D),de(D===ds?{scope:"all"}:{scope:"group",groupKey:D})}function Ce(D){_(D),de({queryClass:D})}function ve(D){const R=M!==D;te(R?D:null),R&&y?.(D)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":o,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:o?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(ue,{tone:"caution",children:"Includes historical data"}):null,X?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:X}):null,Be?e.jsx("span",{className:"text-sm text-secondary",children:Be}):null,rt?e.jsx("span",{className:"text-sm text-secondary",children:rt}):null,s&&p&&n?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!p?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||i,children:i?"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:Pe?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),Pe?e.jsx("select",{id:"advanced-measurement-group",value:O,onChange:D=>He(D.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:Ve.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))}):e.jsx(Er,{ariaLabelledBy:"advanced-measurement-group-label",value:O,options:Ve,onChange:He})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-class-label",className:"block text-sm font-medium text-heading",children:"Query type"}),e.jsx(Er,{ariaLabelledBy:"advanced-measurement-class-label",value:T,options:xh,onChange:Ce,disabled:!p})]}),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:g,onChange:D=>v(D.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!o&&xe?e.jsx(wh,{values:F.shareOfVoice??[]}):null,o?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(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??ce.length," ",(t.currentView?.propertyTotal??ce.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Sh,{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:[oh.map(D=>{const R=Z.startsWith(`${D.key}-`),I=R&&Z.endsWith("-desc")?"descending":R?"ascending":"none";return e.jsx("th",{"aria-sort":I,className:(D.numeric,void 0),children:x?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const be=`${D.key}-${R&&Z.endsWith("-asc")?"desc":"asc"}`;U(be),de({sort:be})},"aria-label":`Sort by ${D.label.toLowerCase()}`,children:[D.label,e.jsx(Ln,{className:`h-3 w-3 transition-transform ${R?"opacity-100":"opacity-0"} ${I==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):D.label},D.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[K.map(D=>{const R=M===D.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:I=>{jh(I.target)||ve(D.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[f?f({id:D.id,name:D.name}):D.name,Tr(D.status)||D.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Tr(D.status)?e.jsx(ue,{tone:D.status.tone,children:D.status.label}):null,D.historical?e.jsx(ue,{tone:"caution",children:"Historical"}):null]}):null,Mr(D)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:Mr(D)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(Hs,{metric:D.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Hs,{metric:D.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{size:"icon",variant:"ghost","aria-expanded":R,"aria-label":R?`Hide details for ${D.name}`:`Show details for ${D.name}`,onClick:()=>ve(D.id),children:e.jsx(Ln,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${R?"rotate-180":""}`,"aria-hidden":"true"})})})]},D.id),R?(D.providers??[]).map(I=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:I.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(Hs,{metric:I.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Hs,{metric:I.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${D.id}:${I.provider}`)):null,R?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Nh,{property:D,onRetryEvidence:N})})},`${D.id}:details`):null]},D.id)}),K.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]})]})}),b&&t.currentView.nextCursor&&c?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",K.length," of ",t.currentView.propertyTotal]}),u?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(A,{size:"sm",variant:"outline",disabled:m,onClick:()=>c(t.currentView.nextCursor),children:m?"Loading…":u?"Retry loading more properties":"Show 50 more"})]}):b?K.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",K.length," of ",t.currentView.propertyTotal]}):null:e.jsx($a,{shown:K.length,total:ce.length,itemLabel:"properties",onShowAll:()=>J(Number.MAX_SAFE_INTEGER)})]}),!o&&!re&&Se>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 (",Se,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,z).map(D=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(ue,{tone:D.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:D.property}),e.jsx("span",{className:"text-secondary",children:D.summary})]},D.id))}),z<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,z).reduce((D,R)=>D+(R.count??1),0)," of ",Se," flagged results"]}),e.jsx(A,{size:"sm",variant:"outline",onClick:()=>P(D=>Math.min(t.flaggedResults.length,D+uh)),children:"Show 50 more"})]}):ie<Se?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ie," of ",Se," flagged results"]}),b&&t.currentView.nextCursor&&c?e.jsx(A,{size:"sm",variant:"outline",disabled:m,onClick:()=>c(t.currentView.nextCursor),children:m?"Loading…":u?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function Ki(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function kh(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 Ph({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:i,onRunMeasurement:o,onRetryReport:m,onViewChange:u,onLoadMore:h,onPropertyExpand:x,onRetryEvidence:c,renderPropertyLink:y,isRunningMeasurement:N,isOpeningSetup:f,isViewLoading:b,isLoadingMore:p,isLoadMoreError:T,viewSearch:_}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&i?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",disabled:f,onClick:i,children:f?"Opening setup…":Ki(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."}),m?e.jsx(A,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry report"}):null]}):a?e.jsx(Ch,{report:a,canEdit:s,onRunMeasurement:o,onRepublishSetup:i,onViewChange:u,onLoadMore:h,onPropertyExpand:x,onRetryEvidence:c,renderPropertyLink:y,isRunningMeasurement:N,isRepublishingSetup:f,isViewLoading:b,isLoadingMore:p,isLoadMoreError:T,viewSearch:_}):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 Ss={numerator:null,denominator:null,reason:"plan_v1"};function Ah(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function qr(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function Rh(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function $h(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Ih(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 Lh(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Th(t){const s=new Map;for(const n of t){const a=Lh(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function Mh(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(f=>[f.stableKey,f])),r=new Map(n.querySnapshots.map(f=>[f.queryId,f.queryText])),i=new Map;for(const f of n.targetQuerySelections){const b=i.get(f.targetKey)??[];b.push(...f.queryIds.map(p=>r.get(p)).filter(p=>!!p)),i.set(f.targetKey,[...new Set(b)])}const o=Th(s.evidence),m=n.executionNodes.reduce((f,b)=>f+b.expectedSnapshots,0),u=s.run?.status==="completed"&&m>0,h=u?m:0,x=u?m:0,c=s.targets.map(f=>{const b=a.get(f.id),p=o.get(f.id)??[],T=p.map($=>({id:`${$.observationId}:${$.usageEdgeId}:${$.sourceUrl}`,kind:Rh($.classification),query:$.queryText,url:$.sourceUrl,tone:$h($.classification),historical:$.historical||$.bridged})),_=p.some($=>$.historical||$.bridged),O=s.run?f.completeness.complete?b?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${f.completeness.executed} of ${f.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:f.id,name:f.label,mentionCoverage:qr(f.mentionCoverage),citationCoverage:qr(f.citationCoverage),status:O,assignedQueries:i.get(f.id)??[],urls:b?.urls.map(Ah)??[],evidence:T,historical:_}}),y=new Map(c.map(f=>[f.id,f])),N=new Map(n.groups.map(f=>[f.stableKey,f]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:h,totalSlots:x,date:Ih(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Ss,mentionCoverage:Ss,citationCoverage:Ss},properties:c},groups:s.groups.map(f=>({id:f.id,label:f.label,confirmedCompetitorCount:N.get(f.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Ss,mentionCoverage:Ss,citationCoverage:Ss},properties:f.targetIds.map(b=>y.get(b)).filter(b=>!!b)}}))},flaggedResults:[]}}const Dh={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function nt(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 Eh(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 qh(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Oh({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[i,o]=l.useState(_o),m=_e({...Uo({client:V,path:{name:t},query:{period:i}}),placeholderData:zr});async function u(){n(!0),r(null);try{await Bo(t,"client",i)}catch(x){const c=x instanceof Ls||x instanceof Error?x.message:"Download failed";r(c)}finally{n(!1)}}if(m.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(m.error){const x=m.error instanceof Error?m.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:x})})}const h=m.data;return h?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.meta.location?` · Location: ${qh(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",Eh(h.meta.generatedAt)]}),a&&e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:a})]}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsx(Fh,{period:i,onChange:o}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:Ie(u),disabled:s,children:[e.jsx(ri,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(zh,{report:h}),e.jsx(Jh,{report:h,audience:"client"}),e.jsx(Gh,{report:h}),e.jsx(Wh,{report:h,audience:"client",projectName:t}),e.jsx(Yh,{report:h})]}):null}function Fh({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Go.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 Or="AI Visibility — Server-Side",Fr="AI engine attention",_h=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,Uh="Live telemetry from your server logs.";function Gh({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(on,{eyebrow:Fr,title:Or,subtitle:Uh}),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:md(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,i=zn(n,"requests",r),o=`${nt(s.verifiedCrawlerHits.current)} verified · ${nt(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,m=zn(s.aiUserFetchHits,"requests",r),h=[zn(s.referralArrivals,"sessions",r),s.referralArrivalsClassSummary].filter(Boolean).join(" · "),x=s.byOperator.filter(c=>c.verifiedHits>0||c.unverifiedHits>0||c.userFetchHits>0||c.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(on,{eyebrow:Fr,title:Or,subtitle:_h(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ca,{label:"AI bot requests observed",value:nt(n.current),subtitle:o}),e.jsx(ca,{label:"AI user-fetch requests",value:nt(s.aiUserFetchHits.current),subtitle:m||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(ca,{label:"AI referral sessions",value:nt(s.referralArrivals.current),subtitle:h})]}),x.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"AI tool"}),e.jsxs("th",{children:["Bot requests (",a,"d)"]}),e.jsxs("th",{children:["User fetches (",a,"d)"]}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:x.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:c.operator}),e.jsx("td",{children:nt(c.verifiedHits+c.unverifiedHits)}),e.jsx("td",{children:nt(c.userFetchHits)}),e.jsx("td",{children:nt(c.referralArrivals)})]},c.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 Bh(t,s){return t.audience==="both"||t.audience===s}const Kh={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function En(t){return Kh[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Vh(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 zh({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,r=a>0?`${s.mentionRate}%`:"—",i=a>0?`When customers asked AI ${a} ${a===1?"query":"queries"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer queries about your business.",o=Vh(t.whatsChanged.mentionRate),m=n.providers.length>0?n.providers.map(En).join(", "):`${nt(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:i}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-positive-400":o.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(la,{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(la,{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(la,{label:"AI tools tested",value:nt(s.providerCount),subtitle:m})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer queries we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"query we asked":"queries we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((u,h)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',u,'"']})]},h))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer queries where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(u=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:En(u.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(u.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[u.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",u.mentionedCount,"/",u.totalCount,")"]})]})]},u.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((u,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:u},h))})]})}function la({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 Qh(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Hh(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Wh({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(c=>Bh(c,s)),r=fd(t,a),i=s==="client",o=Ko(),[m,u]=l.useState(new Set),h=m.size>0?r.filter(c=>!c.targetRef||!m.has(c.targetRef)):r,x=c=>{if(!c.targetRef)return;const y=c.targetRef;u(N=>new Set(N).add(y)),o.mutate({projectName:n,body:{targetRef:y}},{onSuccess:()=>{we({tone:"positive",title:`Dismissed "${c.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:N=>{we({tone:"negative",title:`Couldn't dismiss "${c.title}"`,detail:String(N)}),u(f=>{const b=new Set(f);return b.delete(y),b})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(on,{eyebrow:i?"Action plan":"Agency actions",title:i?"What to do next":"Agency Action Plan",subtitle:i?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),h.length===0?e.jsx(Ta,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:h.map((c,y)=>{const N=c.evidence.length>0?c.evidence:c.why,f=c.why.length>0||c.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:y+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(ue,{tone:zo(c),children:i?Qh(c.horizon):Vo(c.horizon)}),!i&&e.jsx(ue,{tone:"neutral",children:Qo(c.category)}),e.jsx(ue,{tone:"neutral",children:i?Hh(c.confidence):`${Ho(c.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:c.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:c.action}),e.jsx(Zh,{items:N,limit:3,className:"mt-3"}),f&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:i?"See the data behind this":"Evidence details"}),c.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:i?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:c.why.map((b,p)=>e.jsx("li",{children:b},p))})]}),c.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:i?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:c.evidence.map((b,p)=>e.jsx("li",{children:b},p))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:i?"What success looks like:":"Win condition:"})," ",c.successMetric]}),c.targetRef&&!Y()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>x(c),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"})})]},`${c.priority}-${c.title}`)})})]})}function _r({label:t,value:s,displayValue:n,max:a,barClass:r}){const i=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:`${i}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Yh({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=bd(t).slice(0,5),i=s.length>0?Math.max(...s.map(u=>u.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(u=>u.impressions),1):0,m=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(on,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),m?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer queries about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(u=>e.jsx(_r,{label:u.domain+(u.isCompetitor?" (competitor)":""),value:u.count,displayValue:`${nt(u.count)}×`,max:i,barClass:"bg-mono-400/70"},u.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:[nt(a.indexed)," of ",nt(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:nt(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:nt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:nt(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(u=>e.jsx(_r,{label:u.query,value:u.impressions,displayValue:`${nt(u.impressions)} ${u.impressions===1?"search":"searches"}`,max:o,barClass:"bg-info-500/70"},u.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((u,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:u.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Wo(u.action),u.winnabilityClass==="ceded"&&e.jsx(ue,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(Ta,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function Ia(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function La(t){return t==="up"?"↑":t==="down"?"↓":"→"}function oa({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=Ia(s.direction),i=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",o=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:hd(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 ${i}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:La(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function Ur({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=Ia(s.direction),i=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",o=xd(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 ${i}`,children:[nt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:La(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function Xh({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 i=r.deltaAbs>0?"+":"",o=Ia(r.direction),m=o==="positive"?"text-positive-400":o==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?En(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:m,children:[i,r.deltaAbs.toFixed(1),"% ",La(r.direction)]})]},r.provider)})})]})})]})}function Gr({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const 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(i=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(ue,{tone:Dh[i.severity],children:Yo(i.severity)}),i.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",i.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[i.title,r&&i.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",i.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:i.query}),e.jsx("td",{className:"text-xs text-secondary",children:r?En(i.provider):i.provider})]},i.id))})]})})]})}function Jh({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,i=e.jsx(on,{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:[i,e.jsx(Ta,{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:[i,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(oa,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(oa,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(oa,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Ur,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Ur,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Xh,{movements:n.providerMovements,audience:s}),e.jsx(Gr,{insights:n.wins,heading:a?"What got better":"Wins",emptyMessage:a?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(Gr,{insights:n.regressions,heading:a?"What got worse":"Regressions",emptyMessage:a?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function ca({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 on({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 Zh({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((i,o)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:i},o)),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 Ta({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function ex({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[i,o]=l.useState(!1),[m,u]=l.useState(null),[h,x]=l.useState(t.displayName),[c,y]=l.useState(t.canonicalDomain),[N,f]=l.useState(t.country),[b,p]=l.useState(t.language),[T,_]=l.useState(t.ownedDomains??[]),[O,$]=l.useState(""),[g,v]=l.useState(t.aliases??[]),[C,J]=l.useState(""),[z,P]=l.useState(null),[k,U]=l.useState(!1),[M,te]=l.useState(!1),[je,le]=l.useState(""),[Q,de]=l.useState(""),[oe,G]=l.useState(""),[F,w]=l.useState(""),[Z,re]=l.useState(""),[ce,K]=l.useState(null),[xe,q]=l.useState(null);l.useEffect(()=>{a||(x(t.displayName),y(t.canonicalDomain),f(t.country),p(t.language),_(t.ownedDomains??[]),v(t.aliases??[]))},[t,a]);function ie(){r(!1),u(null),x(t.displayName),y(t.canonicalDomain),f(t.country),p(t.language),_(t.ownedDomains??[]),v(t.aliases??[]),$(""),J("")}function Se(){const R=O.trim();R&&(T.includes(R)||_([...T,R]),$(""))}function Xe(R){_(T.filter(I=>I!==R))}function rt(){const R=C.trim();if(!R)return;const I=R.toLowerCase();g.some(be=>be.toLowerCase()===I)||v([...g,R]),J("")}function it(R){v(g.filter(I=>I!==R))}async function Ge(){if(!(!h.trim()||!c.trim()||!N.trim()||!b.trim())){o(!0),u(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:c.trim(),ownedDomains:T,aliases:g,country:N.trim(),language:b.trim()}),r(!1),we({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(R){u(R instanceof Error?R.message:"Failed to save")}finally{o(!1)}}}async function X(){const R=je.trim(),I=Q.trim(),be=oe.trim(),De=F.trim();if(!(!R||!I||!be||!De)){U(!0),P(null);try{const H={label:R,city:I,region:be,country:De};Z.trim()&&(H.timezone=Z.trim()),await Zo(t.name,H),n(),le(""),de(""),G(""),w(""),re(""),te(!1),we({title:"Location added",detail:`${R} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${R}`,dedupeMode:"drop"})}catch(H){P(H instanceof Error?H.message:"Failed to add location")}finally{U(!1)}}}async function Be(R){U(!0),P(null);try{await Jo(t.name,R),n(),we({title:"Location removed",detail:`${R} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${R}`,dedupeMode:"drop"})}catch(I){P(I instanceof Error?I.message:"Failed to remove location")}finally{U(!1)}}async function Ve(R){U(!0),P(null);try{await Xo(t.name,R),n(),we({title:"Default location updated",detail:`${R} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(I){P(I instanceof Error?I.message:"Failed to set default location")}finally{U(!1)}}async function Pe(R){K(R),q(null);try{await ec(t.name,R),we({title:`${R.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(I){q(I instanceof Error?I.message:"Could not download tracking results.")}finally{K(null)}}const He=h!==t.displayName||c!==t.canonicalDomain||N!==t.country||b!==t.language||JSON.stringify(T)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(g)!==JSON.stringify(t.aliases??[]),Ce="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",ve="mb-1 block text-sm font-medium text-secondary",D=je.trim()&&Q.trim()&&oe.trim()&&F.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"})]}),!Y()&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),m&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[m,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>u(null),children:"×"})]}),!Y()&&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:ve,children:"Display name"}),e.jsx("input",{className:Ce,type:"text",value:h,onChange:R=>x(R.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ve,children:"Canonical domain"}),e.jsx("input",{className:Ce,type:"text",value:c,onChange:R=>y(R.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ve,children:"Country"}),e.jsx("input",{className:Ce,type:"text",value:N,onChange:R=>f(R.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:ve,children:"Language"}),e.jsx("input",{className:Ce,type:"text",value:b,onChange:R=>p(R.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ve,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:T.map(R=>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:[R,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Xe(R),"aria-label":`Remove ${R}`,children:"×"})]},R))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ce} flex-1`,type:"text",placeholder:"docs.example.com",value:O,onChange:R=>$(R.target.value),onKeyDown:R=>R.key==="Enter"&&(R.preventDefault(),Se())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!O.trim(),onClick:Se,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ve,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:g.map(R=>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:[R,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>it(R),"aria-label":`Remove ${R}`,children:"×"})]},R))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Ce} flex-1`,type:"text",placeholder:"Facebook",value:C,onChange:R=>J(R.target.value),onKeyDown:R=>R.key==="Enter"&&(R.preventDefault(),rt())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!C.trim(),onClick:rt,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(A,{type:"button",disabled:i||!He||!h.trim()||!c.trim(),onClick:Ie(Ge),children:i?"Saving...":"Save changes"}),e.jsx(A,{type:"button",variant:"outline",disabled:i,onClick:ie,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(R=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:R},R))}):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(R=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:R},R))}):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:[z&&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:[z,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>P(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(R=>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 ${R.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[R.label,R.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:R.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:R.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!Y()&&R.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:k,onClick:()=>{Ve(R.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${R.label} as default location`,children:"Set default"}),!Y()&&e.jsx("button",{type:"button",disabled:k,onClick:()=>{Be(R.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${R.label}`,children:"Remove"})]})})]},R.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),Y()?null:M?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:Ce,type:"text",value:je,onChange:R=>le(R.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:Ce,type:"text",value:Q,onChange:R=>de(R.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:Ce,type:"text",value:oe,onChange:R=>G(R.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:Ce,type:"text",value:F,onChange:R=>w(R.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:Ce,type:"text",value:Z,onChange:R=>re(R.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:k||!D,onClick:Ie(X),children:k?"Adding...":"Add location"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:k,onClick:()=>{te(!1),P(null)},children:"Cancel"})]})]}):e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>te(!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:ce!==null,onClick:Ie(()=>Pe("csv")),children:ce==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ce!==null,onClick:Ie(()=>Pe("json")),children:ce==="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 Vs(t){return{...t??{}}}function tx(t,s){const n=Object.entries(t).sort(([r],[i])=>r.localeCompare(i)),a=Object.entries(s).sort(([r],[i])=>r.localeCompare(i));return n.length===a.length&&n.every(([r,i],o)=>{const m=a[o];return m?.[0]===r&&m[1]===i})}function sx({project:t,onSave:s}){const n=_e({queryKey:["settings"],queryFn:Wr,staleTime:6e4}),[a,r]=l.useState(t.providers.length===0),[i,o]=l.useState(t.providers),[m,u]=l.useState(()=>Vs(t.providerModels)),[h,x]=l.useState({providers:t.providers,providerModels:Vs(t.providerModels)}),[c,y]=l.useState(!1),[N,f]=l.useState(!1),[b,p]=l.useState(null),[T,_]=l.useState(null),O=l.useRef(null),$=n.data?.providerCatalog??[],g=l.useMemo(()=>new Set((n.data?.providers??[]).filter(M=>M.configured).map(M=>M.name)),[n.data]),v=l.useMemo(()=>{const M=new Map($.map(te=>[te.name,te]));for(const te of Object.keys(m))M.has(te)||M.set(te,{name:te,displayName:te,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...M.values()].sort((te,je)=>te.displayName.localeCompare(je.displayName))},[$,m]),C=!tx(m,h.providerModels);l.useEffect(()=>{if(c||N)return;const M={providers:t.providers,providerModels:Vs(t.providerModels)};x(M),r(M.providers.length===0),o(M.providers),u(M.providerModels)},[t]);function J(){f(!0),r(!1),i.length===0&&o([...g])}function z(M,te,je=!1){f(!0),u(le=>{const Q={...le};return te==="__inherit__"?delete Q[M]:te==="__custom__"?Q[M]=je?"":Q[M]??"":Q[M]=te,Q}),te==="__custom__"&&queueMicrotask(()=>O.current?.focus())}function P(M,te){f(!0),o(je=>te?[...new Set([...je,M])]:je.filter(le=>le!==M))}function k(){f(!1),r(h.providers.length===0),o(h.providers),u(Vs(h.providerModels)),p(null),_(null)}async function U(){if(!(n.isError||n.isLoading||!a&&i.length===0)){y(!0),p(null),_(null);try{const M=Object.fromEntries(Object.entries(m).filter(([je,le])=>le.trim()!==""&&(a||i.includes(je)))),te={providers:a?[]:i,providerModels:M};await s(te),x({providers:[...te.providers],providerModels:Vs(te.providerModels)}),f(!1),_("Engine settings saved. They apply on the next sweep.")}catch(M){p(wa(M))}finally{y(!1)}}}return Y()?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"})]}):$.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"})]}):g.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(_t,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":c,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:c,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{f(!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:J})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:v.map(M=>{const te=i.includes(M.name),je=g.has(M.name),le=te&&!je,Q=m[M.name],de=M.knownModels.some(G=>G.id===Q),oe=Q===void 0?"__inherit__":de?Q:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:te,disabled:!je&&!te,onChange:G=>P(M.name,G.target.checked)})," ",e.jsx("span",{children:M.displayName}),le&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),te&&(M.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${M.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${M.name}`,value:oe,onChange:G=>z(M.name,G.target.value,de),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",M.defaultModel||"default"]}),M.knownModels.map(G=>e.jsx("option",{value:G.id,children:G.displayName},G.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),oe==="__custom__"&&e.jsx("input",{ref:O,"aria-label":`${M.displayName} custom model ID`,value:Q??"",onChange:G=>{f(!0),u(F=>({...F,[M.name]:G.target.value}))},"aria-describedby":`project-model-hint-${M.name}`}),e.jsxs("p",{id:`project-model-hint-${M.name}`,className:"project-engine-help",children:[Q?"Project override":"Inherited from instance settings",". ",M.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},M.name)})})]}),!a&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),b&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:b}),T&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:T}),C&&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:()=>{U()},disabled:c||!a&&i.length===0,children:c?"Saving engines…":"Save engines"}),e.jsx(A,{type:"button",variant:"outline",onClick:k,disabled:c,children:"Cancel"})]})]})}const nx=[{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"}],Br=["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 ax({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[i,o]=l.useState("daily"),[m,u]=l.useState(6),[h,x]=l.useState(""),[c,y]=l.useState("UTC"),[N,f]=l.useState(!1),[b,p]=l.useState(""),[T,_]=l.useState(!1),[O,$]=l.useState(!1),[g,v]=l.useState(null);l.useEffect(()=>{tc(t).then(n).catch(()=>n(null))},[t]);const C=()=>{if(s&&s!=="loading"){const k=nc(s.preset??null,s.cronExpr);o(k.freq),u(k.hour),x(k.customCron);const U=Br.includes(s.timezone);y(U?s.timezone:"Other"),f(!U),p(U?"":s.timezone)}else o("daily"),u(6),x(""),y("UTC"),f(!1),p("");v(null),r(!0)},J=async()=>{_(!0),v(null);try{const U={timezone:N?b.trim()||"UTC":c};i==="custom"?U.cron=h.trim():U.preset=rc(i,m);const M=await Ya(t,U);n(M),r(!1),we({title:"Schedule saved",detail:Kn(M.preset??null,M.cronExpr,M.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(k){v(k instanceof Error?k.message:"Failed to save schedule")}finally{_(!1)}},z=async()=>{if(!(!s||s==="loading")){_(!0),v(null);try{const k={timezone:s.timezone,enabled:!s.enabled};s.preset?k.preset=s.preset:k.cron=s.cronExpr;const U=await Ya(t,k);n(U),we({title:U.enabled?"Schedule resumed":"Schedule paused",detail:Kn(U.preset??null,U.cronExpr,U.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(k){v(k instanceof Error?k.message:"Failed to update schedule")}finally{_(!1)}}},P=async()=>{$(!0),v(null);try{await ac(t),n(null),r(!1),we({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(k){v(k instanceof Error?k.message:"Failed to remove schedule")}finally{$(!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"})]}),!Y()&&s!=="loading"&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:C,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===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."})}),s!=="loading"&&!a&&s!==null&&e.jsxs(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:Kn(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ue,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!Y()&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:T,onClick:Ie(z),children:s.enabled?"Pause":"Resume"}),!Y()&&e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:O,onClick:Ie(P),children:O?"Removing...":"Remove"})]})]}),g&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:g})]}),!Y()&&a&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:i,onChange:k=>o(k.target.value),children:nx.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:m,disabled:i==="twice-daily"||i==="custom",onChange:k=>u(parseInt(k.target.value)),children:Array.from({length:24},(k,U)=>e.jsx("option",{value:U,children:sc(U)},U))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:h,onChange:k=>x(k.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:N?"Other":c,onChange:k=>{k.target.value==="Other"?(f(!0),y("Other")):(f(!1),y(k.target.value))},children:[Br.map(k=>e.jsx("option",{value:k,children:k},k)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),N&&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:b,onChange:k=>p(k.target.value)})]}),g&&e.jsx("p",{className:"text-negative-400 text-sm",children:g}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),v(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:T||i==="custom"&&!h.trim(),onClick:Ie(J),children:T?"Saving...":"Save schedule"})]})]})]})}const rx=[{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 ix({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[i,o]=l.useState(""),[m,u]=l.useState(["citation.lost","citation.gained"]),[h,x]=l.useState(!1),[c,y]=l.useState(null),[N,f]=l.useState({}),[b,p]=l.useState(new Set);l.useEffect(()=>{ic(t).then(n).catch(()=>n([]))},[t]);const T=g=>{u(v=>v.includes(g)?v.filter(C=>C!==g):[...v,g])},_=async()=>{if(!(!i.trim()||m.length===0)){x(!0),y(null);try{const g=await lc(t,{channel:"webhook",url:i.trim(),events:m});n(v=>v==="loading"?[g]:[...v,g]),o(""),u(["citation.lost","citation.gained"]),r(!1),we({title:"Webhook added",detail:`Notifications will be sent to ${g.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(g){y(g instanceof Error?g.message:"Failed to add webhook")}finally{x(!1)}}},O=async g=>{if(!b.has(g)){p(v=>new Set(v).add(g));try{await cc(t,g),n(v=>v==="loading"?v:v.filter(C=>C.id!==g)),we({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${g}`,dedupeMode:"drop"})}catch(v){y(v instanceof Error?v.message:"Failed to remove webhook")}finally{p(v=>{const C=new Set(v);return C.delete(g),C})}}},$=async g=>{f(v=>({...v,[g]:{state:"testing"}}));try{const v=await oc(t,g);f(C=>({...C,[g]:{state:v.ok?"ok":"fail",status:v.status}})),v.ok&&we({title:"Test notification sent",detail:`Webhook returned status ${v.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${g}`,dedupeMode:"replace"})}catch{f(v=>({...v,[g]:{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"})]}),!Y()&&s!=="loading"&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),y(null)},children:a?"Cancel":"+ Add webhook"})]}),!Y()&&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:i,onChange:g=>o(g.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:rx.map(g=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:m.includes(g.value),onChange:()=>T(g.value)}),e.jsx("span",{className:"text-sm text-neutral",children:g.label})]},g.value))})]}),c&&e.jsx("p",{className:"text-negative-400 text-sm",children:c}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),y(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:h||!i.trim()||m.length===0,onClick:Ie(_),children:h?"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(g=>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:g.urlHost,children:g.urlDisplay??g.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:g.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(ue,{tone:g.enabled?"positive":"neutral",children:g.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[N[g.id]&&(()=>{const v=N[g.id],C=v.state==="testing"?"Sending…":v.state==="ok"?`Delivered${v.status?` (${v.status})`:""}`:`Failed${v.status?` (${v.status})`:""}`;return e.jsx(ue,{tone:v.state==="ok"?"positive":v.state==="fail"?"negative":"neutral",children:C})})(),!Y()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:N[g.id]?.state==="testing",onClick:()=>{$(g.id)},children:"Test"}),!Y()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:b.has(g.id),onClick:()=>{O(g.id)},children:b.has(g.id)?"Removing…":"Remove"})]})})]},g.id))})]}),c&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:c})]})]})}const Kr=2e3,Vr=3e5;function lx(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 ox({projectName:t,refreshNonce:s}){const n=rs(),[a,r]=l.useState(null),[i,o]=l.useState([]),[m,u]=l.useState(null),[h,x]=l.useState([]),[c,y]=l.useState([]),[N,f]=l.useState(null),[b,p]=l.useState(""),[T,_]=l.useState(""),[O,$]=l.useState(""),[g,v]=l.useState(!0),[C,J]=l.useState(!1),[z,P]=l.useState(null),[k,U]=l.useState("performance");l.useEffect(()=>{M()},[t,s]);async function M(){v(!0),P(null);try{const w=await n.fetchQuery({...si({client:V,path:{name:t}}),staleTime:ut});if(r(w),w.connected){const[Z,re,ce,K]=await Promise.all([n.fetchQuery({...ni({client:V,path:{name:t}}),staleTime:ut}).catch(()=>null),n.fetchQuery({...Dc({client:V,path:{name:t}}),staleTime:ut}).catch(()=>[]),n.fetchQuery({...Ec({client:V,path:{name:t}}),staleTime:ut}).catch(()=>[]),w.siteUrl?Promise.resolve([]):n.fetchQuery({...qc({client:V,path:{name:t}}),staleTime:ut}).then(xe=>xe.sites).catch(()=>[])]);u(Z),x(re),y(ce),o(K)}else u(null),x([]),y([]),o([])}catch(w){P(w instanceof Error?w.message:"Failed to load Bing data")}finally{v(!1)}}async function te(){if(T.trim()){P(null);try{const w=await Oc(t,T.trim());await at(n,"bing"),_(""),w.availableSites.length>0&&o(w.availableSites),await M()}catch(w){P(w instanceof Error?w.message:"Failed to connect")}}}async function je(){try{await Fc(t),await at(n,"bing"),r(null),o([]),u(null),x([]),y([]),f(null),$(""),P(null)}catch(w){P(w instanceof Error?w.message:"Failed to disconnect")}}async function le(){if(O)try{await _c(t,O),await at(n,"bing"),await M()}catch(w){P(w instanceof Error?w.message:"Failed to set site")}}async function Q(){if(b.trim())try{const w=await Uc(t,b.trim());await at(n,"bing"),f(w),x(Z=>[w,...Z])}catch(w){P(w instanceof Error?w.message:"Inspection failed")}}async function de(w){J(!0),P(null);try{const Z=await Ja(t,{urls:[w]}),{succeeded:re,failed:ce,total:K}=Z.summary;we({title:"Bing submission requested",detail:ce===0?`${re} URL submitted to Bing.`:`${re}/${K} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${w}`,dedupeMode:"replace"})}catch(Z){const re=Z instanceof Error?Z.message:"Submission failed";P(re),we({title:"Bing submission failed",detail:re,tone:"negative",dedupeKey:`bing:indexing:${t}:${w}`,dedupeMode:"replace"})}finally{J(!1)}}async function oe(){J(!0),P(null),we({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const w=await Ja(t,{allUnindexed:!0}),{succeeded:Z,failed:re,total:ce}=w.summary;we({title:"Bing submissions requested",detail:re===0?`${Z}/${ce} URL${ce!==1?"s":""} submitted to Bing.`:`${Z}/${ce} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(w){const Z=w instanceof Error?w.message:"Batch submission failed";P(Z),we({title:"Bing submissions failed",detail:Z,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{J(!1)}}if(g)return e.jsx(he,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return Y()?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(ue,{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(ue,{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:T,onChange:w=>_(w.target.value),onKeyDown:w=>{w.key==="Enter"&&te()}}),e.jsx(et,{size:"sm",disabled:!T.trim(),onClick:Ie(te),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"})]})]}),z&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:z})]});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(ue,{tone:"positive",children:"Connected"}),!Y()&&e.jsx(et,{size:"sm",variant:"ghost",onClick:Ie(je),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?Ot(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"}),i.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:O,onChange:w=>$(w.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),i.map(w=>e.jsxs("option",{value:w.url,children:[w.url,w.verified?" (verified)":""]},w.url))]}),!Y()&&e.jsx(et,{size:"sm",disabled:!O,onClick:Ie(le),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."})]})]}),z&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:z})]});const G=[{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"}],F=G.find(w=>w.key===k)??G[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(ue,{tone:"positive",children:"Connected"}),!Y()&&e.jsx(et,{size:"sm",variant:"ghost",onClick:Ie(je),children:"Disconnect"})]})]}),z&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:z}),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?Ot(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:F.eyebrow}),e.jsx("h3",{children:F.title})]}),e.jsx("p",{className:"text-xs text-muted",children:m?.lastInspectedAt?`Last inspected ${Ot(m.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:G.map(w=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${k===w.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>U(w.key),children:w.label},w.key))}),k==="coverage"&&m&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(gn,{label:"Indexed",value:m.summary.indexed,tone:"positive"}),e.jsx(gn,{label:"Not in index",value:m.summary.notIndexed+(m.summary.unknown??0),tone:"negative"}),e.jsx(gn,{label:"Status unknown",value:m.summary.unknown??0,tone:"neutral"}),e.jsx(gn,{label:"Coverage",value:`${m.summary.percentage}%`,tone:"neutral"})]}),m.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",m.notIndexed.length,")"]}),!Y()&&e.jsx(et,{size:"sm",variant:"ghost",disabled:C,onClick:Ie(oe),children:C?"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"}),!Y()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:m.notIndexed.map(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.httpCode??"—"}),!Y()&&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:C,onClick:()=>{de(w.url)},children:"Submit"})})]},w.id))})]})})]}),(m.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(m.unknown??[]).length,")"]}),!Y()&&e.jsx(et,{size:"sm",variant:"ghost",disabled:C,onClick:Ie(oe),children:C?"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"}),!Y()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(m.unknown??[]).map(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.lastCrawledDate?Ot(w.lastCrawledDate):"—"}),!Y()&&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:C,onClick:()=>{de(w.url)},children:"Submit"})})]},w.id))})]})})]}),m.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",m.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:m.indexed.map(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.lastCrawledDate?Ot(w.lastCrawledDate):"—"})]},w.id))})]})})]})]}),k==="coverage"&&!m&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),k==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!Y()&&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:b,onChange:w=>p(w.target.value),onKeyDown:w=>{w.key==="Enter"&&Q()}}),e.jsx(et,{size:"sm",disabled:!b.trim(),onClick:Ie(Q),children:"Inspect"})]}),N&&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:N.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:N.inIndex?"text-positive-400":"text-negative-400",children:N.inIndex?"Yes":"No"})," · ","HTTP: ",N.httpCode??"—"," · ","Crawled: ",N.lastCrawledDate??"—"]})]}),h.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:h.map(w=>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:w.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ue,{tone:w.inIndex?"positive":"negative",children:w.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:w.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Ot(w.inspectedAt)})]},w.id))})]})})]}),k==="performance"&&e.jsx("div",{className:"mt-4",children:c.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:pn[hs.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:pn[hs.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:pn[hs.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:pn[hs.Position]})]})}),e.jsx("tbody",{children:c.map((w,Z)=>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:w.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:w.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:w.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(w.ctr)?w.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:w.averagePosition.toFixed(1)})]},Z))})]})})})]})]})}function cx({projectName:t}){const s=rs(),[n,a]=l.useState("google"),[r,i]=l.useState(!0),[o,m]=l.useState("idle"),[u,h]=l.useState(null),x=l.useRef(null),[c,y]=l.useState(!1),[N,f]=l.useState(null),[b,p]=l.useState(null),[T,_]=l.useState(!1),[O,$]=l.useState(null),[g,v]=l.useState(null),[C,J]=l.useState(0);async function z(G=!1){G||i(!0),h(null);try{const[F,w,Z]=await Promise.all([s.fetchQuery(Zr({client:V})).catch(()=>null),s.fetchQuery({...Na({client:V,path:{name:t}}),staleTime:ut}).catch(()=>[]),s.fetchQuery({...si({client:V,path:{name:t}}),staleTime:ut}).catch(()=>null)]),re=w.find(xe=>xe.connectionType==="gsc")??null;y(!!F?.google?.configured),_(!!F?.bing?.configured),f(re),$(Z);const[ce,K]=await Promise.all([re?s.fetchQuery({...Yr({client:V,path:{name:t}}),staleTime:ut}).catch(()=>null):Promise.resolve(null),Z?.connected?s.fetchQuery({...ni({client:V,path:{name:t}}),staleTime:ut}).catch(()=>null):Promise.resolve(null)]);p(ce),v(K)}catch(F){h(F instanceof Error?F.message:"Failed to load search console overview")}finally{i(!1)}}async function P(){if(o!=="idle")return;x.current?.abort();const G=new AbortController;x.current=G;const F=G.signal;m("syncing"),h(null),we({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const w=[],Z=[];try{async function re(){if(!N)return;const xe=await Tc(t);if(!xe?.id)return;const q=Date.now()+Vr;for(;Date.now()<q;){if(F.aborted||(await new Promise(Se=>setTimeout(Se,Kr)),F.aborted))return;const ie=await ua(xe.id).catch(()=>null);if(!ie)break;if(["completed","failed","cancelled"].includes(ie.status)){ie.status!=="completed"&&w.push(`Google sync ${ie.status}`);return}}Z.push("Google sync is still running — search data will appear shortly")}async function ce(){if(!O?.connected)return;const xe=await Mc(t).catch(()=>null);if(!xe?.id){w.push("Bing sweep could not be started");return}const q=Date.now()+Vr;for(;Date.now()<q;){if(F.aborted||(await new Promise(Se=>setTimeout(Se,Kr)),F.aborted))return;const ie=await ua(xe.id).catch(()=>null);if(!ie)break;if(["completed","failed","cancelled","partial"].includes(ie.status)){ie.status==="failed"?w.push("Bing sweep failed"):ie.status==="partial"&&Z.push("Bing sweep finished with some pages unverified");return}}Z.push("Bing sweep is still running — coverage will update shortly")}const K=await Promise.allSettled([re(),ce()]);for(const xe of K)xe.status==="rejected"&&w.push(xe.reason instanceof Error?xe.reason.message:"Sync failed");if(await Promise.all([at(s,"gsc"),at(s,"bing")]),F.aborted)return;if(m("reloading"),await z(!0),J(xe=>xe+1),w.length>0){const xe=`Partial refresh: ${[...w,...Z].join("; ")}`;h(xe),we({title:"Search coverage partially refreshed",detail:xe,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else Z.length>0?we({title:"Search coverage refresh incomplete",detail:Z.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):we({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(re){if(!F.aborted){const ce=re instanceof Error?re.message:"Refresh failed";h(ce),we({title:"Search coverage refresh failed",detail:ce,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{F.aborted||m("idle")}}l.useEffect(()=>(z(),()=>{x.current?.abort()}),[t]);const k=N?"positive":c?"caution":"negative",U=N?"Connected":c?"Ready to connect":"Needs setup",M=b?`${b.summary.percentage}% indexed`:N?"Awaiting coverage":"No coverage data",te=b?`${b.summary.notIndexed} not indexed${b.summary.deindexed>0?` · ${b.summary.deindexed} deindexed`:""}`:N?"Run sitemap inspection to populate coverage":c?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",je=O?.connected?"positive":T?"caution":"negative",le=O?.connected?"Connected":T?"Ready to connect":"Needs setup",Q=g?`${g.summary.percentage}% indexed`:O?.connected?"Awaiting coverage":"No coverage data",de=g?g.summary.notIndexed+(g.summary.unknown??0):0,oe=g?`${de} not in index`:O?.connected?"Inspect URLs to populate coverage":T?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings";return e.jsxs("div",{className:"space-y-6",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:"Search engines"}),e.jsx("h2",{children:"Coverage and performance"})]}),!Y()&&e.jsxs(et,{type:"button",variant:"outline",size:"sm",disabled:r||o!=="idle",onClick:()=>{P()},children:[e.jsx($n,{className:`h-3.5 w-3.5 ${o!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"]})]}),u&&e.jsx("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("div",{className:"mt-4 divide-y divide-default border-y border-default",children:[["Google Search Console",r?"Loading…":U,r?"neutral":k,r?"Loading overview…":te,M],["Bing Webmaster Tools",r?"Loading…":le,r?"neutral":je,r?"Loading overview…":oe,Q]].map(([G,F,w,Z,re])=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:G}),e.jsx("span",{className:"ml-2 text-secondary",children:Z})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"tabular-nums text-secondary",children:re}),e.jsx(ue,{tone:w,children:F})]})]},G))})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([G,F])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===G,className:`project-subnav-link ${n===G?"project-subnav-link-active":""}`,onClick:()=>a(G),children:F},G))}),n==="google"&&e.jsx(eu,{projectName:t,refreshNonce:C}),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(ox,{projectName:t,refreshNonce:C})]})]})}function Js({label:t,summary:s,displayValue:n,tooltip:a}){const r=s.value.trim()!==""&&Number.isFinite(Number(s.value)),i=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 ${Cc[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:`${i}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function dx({model:t,sweepRunning:s}){const n=t.citationMovement,a=t.mentionMovement,r=t.movementComparison,i=t.recentRuns.find(y=>y.kind===en["answer-visibility"]),o=y=>y.tone==="positive"?"improved":y.tone==="negative"?"declined":y.gained>0||y.lost>0?"mixed":"steady",m=o(a),u=o(n),h=(()=>{if(s)return"A fresh sweep is running now";if(!r.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(r.querySetChanged)return"Tracking scope changed since the previous sweep";if(m===u)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 y=m==="mixed"?"Answer mention movement was mixed":m==="steady"?"Answer mentions held steady":`Answer mentions ${m}`,N=u==="mixed"?"citation movement was mixed":u==="steady"?"citation coverage held steady":`citation coverage ${u}`;return`${y}; ${N}`})(),x=[r.addedQueryCount>0&&`${r.addedQueryCount} ${r.addedQueryCount===1?"query":"queries"} added`,r.removedQueryCount>0&&`${r.removedQueryCount} ${r.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),c=`${r.comparableQueryCount} comparable ${r.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:h})]}),e.jsx("p",{className:"overview-brief-updated",children:i?`Updated ${i.startedAt}`:"No completed sweep"})]}),e.jsxs("div",{className:"overview-brief-grid",children:[e.jsxs("div",{className:"overview-brief-panel overview-brief-coverage",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage now"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Js,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Js,{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"}),r.hasPreviousRun?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overview-signal-change-list",children:[e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Mentioned"}),a.gained===0&&a.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[a.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",a.gained]}),a.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",a.lost]})]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),n.gained===0&&n.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[n.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",n.gained]}),n.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",n.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${r.querySetChanged?"text-caution-400/80":""}`,children:r.querySetChanged?`${x||"Query set changed"} · ${c}.`:`${c}.`})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No comparison yet"}),e.jsx("p",{className:"overview-brief-panel-copy",children:"Run another sweep to measure mention and citation movement."})]})]})]})]})}function da({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:i}){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(Ln,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:i})]})}function ux({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const a=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(a===0)return null;const r=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(o=>({label:o.domain,mentions:o.mentionSnapshots,isYou:!1}))].sort((o,m)=>m.mentions-o.mentions),i=r[0]?.mentions??1;return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsx("p",{className:"mention-share-breakdown-title",children:"Mention share breakdown · latest run"}),e.jsx("ul",{className:"mention-share-breakdown-rows",children:r.map(o=>{const m=o.mentions/a*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${o.isYou?"text-heading font-medium":"text-secondary"}`,children:o.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${o.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${Math.max(o.mentions/i*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:o.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[m.toFixed(1),"%"]})]},o.label)})})]})}function mx({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=Qr(),r=ti(),[i,o]=l.useState(new Set);if(t.length===0&&s.rows.length===0)return null;const m=p=>{o(T=>{const _=new Set(T);return _.delete(p),_})},u=p=>{o(T=>new Set(T).add(p)),r.mutate({projectName:n,queries:[p]},{onSuccess:()=>{we({tone:"positive",title:`Tracking "${p}"`}),m(p)},onError:T=>{we({tone:"negative",title:`Could not track "${p}"`,detail:String(T)}),m(p)}})},h=p=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:p.title}),p.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:p.detail}):null]}),e.jsx(ue,{tone:p.tone,children:p.actionLabel})]}),p.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",p.affectedPhrases.length," affected ",p.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:p.affectedPhrases.map((T,_)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ma,{state:T.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:T.query}),T.provider?e.jsx(Is,{provider:T.provider}):null,!Y()&&T.evidenceId?e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(T.evidenceId)},children:"View evidence"}):null]},T.evidenceId||`${p.id}-${_}`))})]}):null]},p.id),x=p=>{const T=i.has(p.query);return e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:p.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:p.reason})]}),Y()?null:e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:T,"aria-label":`Track query "${p.query}"`,onClick:()=>u(p.query),children:T?"Tracking…":"Track"})]},p.query)},c=t.slice(0,1),y=s.rows.slice(0,1),N=t.slice(1),f=s.rows.slice(1),b=N.length+f.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[c.map(h),y.map(x)]}),b>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[b," more ",b===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[N.map(h),f.map(x)]})]}):null]})}function Ax(t){const{projectName:s}=tl({from:"/projects/$projectName"}),a=dc()?.dashboard.projects.find(y=>y.project.name===s||y.project.id===s)?.project.name??null,r=_e({...uc({client:V}),enabled:!a}),i=a??r.data?.find(y=>y.name===s||y.id===s)?.name??null,{commandCenter:o,isLoading:m,latestVisibilityRevision:u,refetch:h}=mc(i),x=!a&&r.isLoading||m;return!i&&!a&&r.isSuccess&&!m?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(_t,{to:"/",children:"Return to overview"})})]})}):!o||x?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(y=>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"})]},y))}),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(y=>e.jsx("div",{className:"skeleton-text-sm w-full"},y))})]})]}):e.jsx(xx,{model:o,refetch:h,latestVisibilityRevision:u,...t})}function hx({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const o=u=>{r.current&&!r.current.contains(u.target)&&a(!1)},m=u=>{u.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",m)}},[n]),t.length===0)return null;const i=t.some(o=>o.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 ${i?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(o=>!o),children:["More",e.jsx(Ln,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(o=>e.jsx(_t,{to:o.href,role:"menuitem",className:`project-subnav-menu-item ${o.key===s?"project-subnav-menu-item-active":""}`,"aria-current":o.key===s?"page":void 0,onClick:()=>a(!1),children:o.label},o.key))}):null]})}function xx({tab:t,model:s,refetch:n,latestVisibilityRevision:a}){const r=sl(),i=rs(),{canWrite:o}=hc(),m=l.useMemo(()=>{const j=xc();return j?pc(j.projectTabs):void 0},[]),u=gc(t,m),h=l.useMemo(()=>s.competitors.map(j=>j.domain),[s.competitors]),[x,c]=l.useState(!1),[y,N]=l.useState(!1),f=ti(),b=nl({strict:!1}),p=b.manageQueries===!0,T=l.useCallback(()=>{r({to:".",replace:!0,search:j=>({...j,siteHealthRunId:void 0})})},[r]),[_,O]=l.useState(p),[$,g]=l.useState(""),[v,C]=l.useState(!1),[J,z]=l.useState(null),[P,k]=l.useState(!1),[U,M]=l.useState(""),[te,je]=l.useState(!1),[le,Q]=l.useState(void 0),[de,oe]=l.useState(!1),[G,F]=l.useState(null),[w,Z]=l.useState(null),[re,ce]=l.useState(!1),K=vd(b),[xe,q]=l.useState(void 0),[ie,Se]=l.useState(void 0),Xe=l.useCallback(j=>{q(j.search),j.sort&&Se(j.sort),r({to:".",search:ge=>({...ge,...wd(j)}),replace:!1})},[r]),[rt,it]=l.useState(!1),Ge=s?.visibilityEvidence??[],X=s?.project.name??"",Be=s?.project.displayName||s?.project.name||X,Ve=fc(),Pe=_e({...bc({client:V,path:{name:X}}),enabled:u==="portfolio"&&!!X,staleTime:0,refetchOnMount:"always"}),He=_e({...yc({client:V,path:{name:X}}),enabled:!Y()&&!!X,retry:!1}),Ce=_e({...jc({client:V,path:{name:X}}),enabled:!Y()&&(u==="portfolio"||u==="overview"||u==="settings")&&!!X,staleTime:0,refetchOnMount:"always"}),ve=_e({...vc({client:V,path:{name:X}}),enabled:!Y()&&(u==="portfolio"||u==="overview"||u==="settings")&&!!X,staleTime:0,refetchOnMount:"always"}),D=He.data,R=D?.enabled&&D.nextRunAt?`Next AI sweep ${new Date(D.nextRunAt).toLocaleString()}`:null,I=Ce.data?.active??null,be=Ce.data!==void 0,De=new Set(I&&Number(I.plan.schemaVersion)===2?I.plan.groups?.map(j=>j.stableKey)??[]:[]),Ee={...K.scope==="group"&&!!K.groupKey&&be&&!De.has(K.groupKey)?{scope:"all",queryClass:K.queryClass}:K,...xe?{search:xe}:{}},lt=I===null?null:Number(I.plan.schemaVersion),bt=I?.revision??0,ke=be?`${X}:${bt}`:null,Oe=l.useRef(null);l.useEffect(()=>{const j=Oe.current;ke!==null&&(Oe.current=ke),Nd(j,ke)&&(Xe({scope:"all",queryClass:"all"}),it(!1))},[ke,Xe]);const ht={client:V,path:{name:X},query:{scope:Ee.scope,...Ee.groupKey?{groupKey:Ee.groupKey}:{},queryClass:Ee.queryClass,...Ee.search?{search:Ee.search}:{},...ie?{sort:ie}:{},limit:50}},Ue=al({...Nc(ht),enabled:u==="overview"&&!!X&<===2,initialPageParam:ht,getNextPageParam:(j,ge)=>{if(!j.properties.nextCursor)return;const ye=ge[0]?.measurement.displayedRunId;return{path:ht.path,query:{...ht.query,cursor:j.properties.nextCursor,...ye?{runId:ye}:{}}}},placeholderData:zr,staleTime:0,refetchOnMount:"always"}),We=Ue.data?.pages[0]?.measurement.displayedRunId,Ae=_e({...wc({client:V,path:{name:X},query:{revision:bt,...We?{runId:We}:{}}}),enabled:u==="overview"&&!!X&&I!==null&&(lt===1||rt&&We!==void 0),staleTime:0,refetchOnMount:"always"}),jt=Ce.data!==void 0,Ct=Pe.data!==void 0,Le=Ce.isPending&&!jt,Te=Ce.isError&&!jt,ot=Pe.isPending&&!Ct,Fe=Pe.isError&&!Ct,Tt=Ae.data!==void 0,vt=kh({activePlanSchemaVersion:ve.data?.activeSchemaVersion??lt,hasDraft:ve.data?.draft!==null&&ve.data?.draft!==void 0}),pt=ve.data===void 0&&Ce.data===void 0&&(Ce.isLoading||ve.isLoading),Je=ve.data!==void 0?"success":ve.isError?"error":"pending",E=l.useMemo(()=>{const j=Ue.data?.pages;return j?!od(j):!1},[Ue.data]),Ne=l.useMemo(()=>{const j=Ue.data?.pages,ge=j?.[0],ye=j?.at(-1);if(!(!ge||!ye||E))return{...ge,properties:{...ge.properties,items:j.flatMap(S=>S.properties.items),nextCursor:ye.properties.nextCursor}}},[E,Ue.data]),me=l.useMemo(()=>{if(I)return I.plan.schemaVersion===1?Ae.data?Mh(I,Ae.data):void 0:Ne?cd({overview:Ne,activePlan:I,sort:ie,report:Ae.data,reportState:Ne.measurement.displayedRunId===void 0?"ready":Ae.isFetching&&Ae.data===void 0?"loading":Ae.isError&&Ae.data===void 0?"error":Ae.data?"ready":"loading"}):void 0},[I,Ae.data,Ae.isError,Ae.isFetching,Ne]),fe=lt===2?E?"error":Ue.isPending?"loading":Ue.isError&&me===void 0?"error":"ready":Ae.isPending&&!Tt?"loading":Ae.isError&&!Tt?"error":"ready",kt=(s?.recentRuns??[]).some(j=>j.kind===en["answer-visibility"]&&(j.status===Xa.running||j.status===Xa.queued)),Mt=l.useMemo(()=>(s?.project.locations??[]).map(j=>j.label),[s?.project.locations]),tt=l.useMemo(()=>new Set(Ge.map(j=>j.location??"")),[Ge]),Pt=tt.has(""),is=l.useMemo(()=>[...new Set(Ge.map(j=>j.query))].sort((j,ge)=>j.localeCompare(ge)),[Ge]),Ds=l.useMemo(()=>{const j=[...tt].filter(Boolean);return j.length>1?j:Mt},[tt,Mt]);l.useEffect(()=>{if(le===void 0||le===""||!X){Z(null),ce(!1);return}ce(!0),Sc(X,le,20).then(j=>{Z(j),ce(!1)}).catch(()=>{Z(null),ce(!1)})},[le,X]);const Dt=l.useMemo(()=>{if(!w)return null;const j=new Map;for(const ge of w){for(const[ye,S]of Object.entries(ge.providerRuns??{}))j.set(`${ge.query}::${ye}`,S.map(B=>({runId:B.runId,citationState:B.citationState,createdAt:B.createdAt,answerMentioned:B.answerMentioned,visibilityState:B.visibilityState,visibilityTransition:B.visibilityTransition,mentionState:B.mentionState,mentionTransition:B.mentionTransition})));(!ge.providerRuns||Object.keys(ge.providerRuns).length===0)&&j.set(`${ge.query}::`,ge.runs.map(ye=>({runId:ye.runId,citationState:ye.citationState,createdAt:ye.createdAt,answerMentioned:ye.answerMentioned,visibilityState:ye.visibilityState,visibilityTransition:ye.visibilityTransition,mentionState:ye.mentionState,mentionTransition:ye.mentionTransition})))}return j},[w]),Es=l.useMemo(()=>{let j=le!==void 0?Ge.filter(ge=>le===""?!ge.location:ge.location===le):Ge;if(G){const ge=G.toLowerCase();j=j.filter(ye=>ye.competitorDomains.some(S=>S.toLowerCase()===ge))}return Dt?j.map(ge=>{const ye=Dt.get(`${ge.query}::${ge.provider}`)??Dt.get(`${ge.query}::`);return ye?{...ge,runHistory:ye}:ge}):j},[Ge,le,G,Dt]);async function Ze(){try{await Ve.mutateAsync({projectName:X,projectLabel:Be,sourceAction:"project-run"}),n()}catch{}}async function qs(){N(!0);try{await Lc(X),we({title:"Project deleted",detail:`${Be} was removed.`,tone:"positive",dedupeKey:`project:delete:${X}`,dedupeMode:"drop"}),r({to:"/"}),n()}catch(j){console.error("Failed to delete project:",j)}finally{N(!1)}}async function Nt(){const j=$.split(`
|
|
8
|
+
`).map(ge=>ge.trim()).filter(Boolean);if(j.length!==0){C(!0);try{await Rc(X,j),n(),g("")}finally{C(!1)}}}async function Os(j){z(j);try{await Ac(X,[j]),n()}catch(ge){we({title:"Could not remove query",detail:ge instanceof Error?ge.message:`Failed to remove "${j}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{z(null)}}async function Qt(){const j=U.trim();if(j){je(!0);try{await kc(X,[j]),n(),M(""),k(!1)}finally{je(!1)}}}async function ys(j){const ge=s.competitors.find(ye=>ye.domain===j);if(!ge){we({title:"Could not remove competitor",detail:`Could not find ${j} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await Pc(X,ge.id),n()}catch(ye){we({title:"Could not remove competitor",detail:ye instanceof Error?ye.message:`Failed to remove ${ge.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function ls(j,ge){const ye=await $c(j,ge);return await i.invalidateQueries({queryKey:ei({client:V})}),i.setQueryData(Ic({client:V,path:{name:j}}),ye),lx(i,ye),ye}const Ye=`/projects/${encodeURIComponent(s.project.name)}`,js=[{key:"overview",label:"AI Visibility",href:Ye},{key:"search-console",label:"Search Engines",href:`${Ye}/search-console`},{key:"activity",label:"Activity",href:`${Ye}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Ye}/technical-aeo`},{key:"local",label:"Local Presence",href:`${Ye}/local`},{key:"discovery",label:"Query Discovery",href:`${Ye}/discovery`},{key:"backlinks",label:"Backlinks",href:`${Ye}/backlinks`}],Et=[{key:"report",label:"Report",href:`${Ye}/report`},{key:"history",label:"Change History",href:`${Ye}/history`}],yt=js.filter(j=>Vn(j.key,m)),vs=Et.filter(j=>Vn(j.key,m)),st=Vn("settings",m)?{key:"settings",label:"Settings",href:`${Ye}/settings`}:null;function Ht(j,ge=!1){const ye=document.getElementById(j);if(!ye)return;ge&&ye instanceof HTMLDetailsElement&&(ye.open=!0);const S=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{ye.scrollIntoView({behavior:S?"auto":"smooth",block:"start"}),(ye instanceof HTMLDetailsElement?ye.querySelector("summary"):ye)?.focus({preventScroll:!0})})}return e.jsxs("div",{className:"page-container",children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]}),!Y()&&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(j=>e.jsx("span",{className:"tag",children:j},j))]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!Y()&&e.jsxs("div",{className:"flex items-center gap-3",children:[R?e.jsx("p",{className:"text-sm text-secondary",children:R}):null,e.jsx(et,{type:"button",variant:"outline",disabled:Ve.isPending||kt,onClick:Ie(Ze),children:Ve.isPending?"Starting…":kt?"AI sweep running…":"Run AI sweep"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[yt.map(j=>e.jsx(_t,{to:j.href,className:`project-subnav-link ${j.key===u?"project-subnav-link-active":""}`,"aria-current":j.key===u?"page":void 0,children:j.label},j.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(hx,{items:vs,activeTab:u}),st&&e.jsx(_t,{to:st.href,className:`project-subnav-link ${u==="settings"?"project-subnav-link-active":""}`,"aria-current":u==="settings"?"page":void 0,children:st.label},st.key)]})]}),u==="portfolio"&&!Y()?e.jsx(lh,{projectName:X,canEdit:o,queries:Pe.data??[],isQueryLoading:ot,isQueryError:Fe,onRetryQueries:()=>{Pe.refetch()},publishedPlan:I,onCreateQueries:async j=>(await f.mutateAsync({projectName:X,queries:[...j]}),(await Pe.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{r({to:"/projects/$projectName",params:{projectName:X},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([ve.refetch(),Ce.refetch()]).finally(()=>{r({to:"/projects/$projectName",params:{projectName:X}})})}},X):u==="overview"?pt?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:[Te?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:()=>{Ce.refetch()},children:"Retry setup check"})]}):null,e.jsx(Ph,{mode:vt,canEdit:o&&!Y()&&!Le&&!Te,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(om,{projectName:s.project.name,competitorDomains:h,analyticsRevision:a})}),e.jsx(dx,{model:s,sweepRunning:kt}),e.jsx(mx,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:s.project.name}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),!Y()&&e.jsx(et,{type:"button",variant:"outline",size:"sm",onClick:()=>k(!P),children:P?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Js,{label:"Mention share",summary:s.mentionShareSummary,tooltip:"Of all brand mentions in answer text across your tracked queries (you + tracked competitors), the percentage that were you. Measured from the latest sweep."}),e.jsx(Js,{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(Js,{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(ux,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name})]}),P&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"competitor.com",value:U,onChange:j=>M(j.target.value),onKeyDown:j=>{j.key==="Enter"&&Qt()}}),e.jsx(et,{type:"button",size:"sm",disabled:!U.trim()||te,onClick:Ie(Qt),children:te?"Adding...":"Add"})]}),s.competitors.length>0&&e.jsxs("details",{className:"inline-disclosure mt-4",children:[e.jsx("summary",{children:"Review tracked competitors"}),e.jsx("div",{className:"mt-3",children:e.jsx(Td,{competitors:s.competitors,onSelectCompetitor:j=>{F(j),Ht("evidence-section",!0)},onRemoveCompetitor:Y()?void 0:j=>{ys(j)},activeFilter:G})})]})]}),e.jsxs(da,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:Y(),children:[!Y()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(et,{type:"button",variant:"outline",size:"sm",onClick:()=>O(!_),children:_?"Done":"Manage queries"})}),!Y()&&_&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[is.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:is.map(j=>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:j,children:j}),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 ${j}`,title:`Stop tracking "${j}"`,disabled:J!==null,onClick:()=>{Os(j)},children:J===j?"Removing…":"Remove"})]},j))}):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:j=>g(j.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(j=>j.trim()).length," to add"]}),e.jsx(et,{type:"button",size:"sm",disabled:!$.trim()||v,onClick:Ie(Nt),children:v?"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 ${le===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":le===void 0,onClick:()=>{Q(void 0)},children:"All locations"}),s.project.locations.map(j=>e.jsx("button",{className:`filter-chip ${le===j.label?"filter-chip-active":""}`,type:"button","aria-pressed":le===j.label,onClick:()=>{Q(j.label),oe(!1)},children:j.label},j.label)),Pt&&e.jsx("button",{className:`filter-chip ${le===""?"filter-chip-active":""}`,type:"button","aria-pressed":le==="",onClick:()=>{Q(""),oe(!1)},children:"No location"}),Ds.length>1&&le===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${de?"filter-chip-active":""}`,type:"button","aria-pressed":de,onClick:()=>oe(j=>!j),title:"Side-by-side location comparison",children:"Compare"})]}),G&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-negative-900/40 bg-negative-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-negative-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-strong",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:G})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>F(null),children:"Clear filter ×"})]}),e.jsx(Rd,{evidence:Es,compareLocations:de})]}),e.jsxs(da,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:Y(),children:[e.jsx(Pu,{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(j=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Is,{provider:j.provider}),j.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:j.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[j.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[j.cited," of ",j.total]})]},`${j.provider}::${j.model??"unknown"}`))})]})})]})]}),!Y()&&e.jsx(da,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(j=>e.jsx(Gc,{run:j},j.id))})})]}),report:me,reportState:fe,onOpenSetup:Y()?void 0:()=>{r({to:"/projects/$projectName/portfolio",params:{projectName:X}})},onRetryReport:()=>{lt===2?Promise.all([Ue.refetch(),Ae.refetch()]):Ae.refetch()},onViewChange:j=>{Xe({scope:j.scope,...j.groupKey?{groupKey:j.groupKey}:{},queryClass:j.queryClass,...j.search?.trim()?{search:j.search.trim()}:{}})},onLoadMore:j=>{j===Ne?.properties.nextCursor&&Ue.fetchNextPage()},onPropertyExpand:()=>{rt&&Ae.isError&&Ae.refetch(),it(!0)},onRetryEvidence:()=>{Ae.refetch()},renderPropertyLink:lt===2&&!Y()?({id:j,name:ge})=>e.jsx(_t,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:X,targetKey:j},className:"text-link hover:underline",children:ge}):void 0,isViewLoading:Ue.isPlaceholderData,isLoadingMore:Ue.isFetchingNextPage,isLoadMoreError:Ue.isFetchNextPageError,viewSearch:Ee.search??""},`${X}:${bt}`)]}):u==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(ex,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(j,ge)=>{await ls(j,ge)},onRefresh:()=>{n()}}),e.jsx(sx,{project:s.project,onSave:async j=>{await ls(s.project.name,j)}}),o&&!Y()?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."}),Je==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):Je==="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:()=>{ve.refetch()},children:"Retry"})]}):e.jsx(A,{type:"button",variant:"outline",onClick:()=>{r({to:"/projects/$projectName/portfolio",params:{projectName:X}})},children:Ki(vt.setupAction)})]}):null,e.jsx(ax,{projectName:s.project.name}),e.jsx(ix,{projectName:s.project.name}),o&&!Y()?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."}),x?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:y,onClick:Ie(qs),children:y?"Deleting...":"Yes, delete project"}),e.jsx(A,{type:"button",variant:"outline",disabled:y,onClick:()=>c(!1),children:"Cancel"})]})]}):e.jsxs(et,{type:"button",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Zc,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):u==="report"?e.jsx(Oh,{projectName:s.project.name}):u==="discovery"?e.jsx(fm,{projectName:X}):u==="technical-aeo"?e.jsx(Kc,{projectName:s.project.name,projectId:s.project.id,initialRunId:b.siteHealthRunId,onReleaseInitialRun:T}):u==="history"?e.jsx(wm,{projectName:s.project.name}):u==="activity"?e.jsx(Ud,{projectName:s.project.name}):u==="backlinks"?e.jsx(ku,{projectName:s.project.name}):u==="local"?e.jsx(su,{projectName:s.project.name,projectId:s.project.id}):u==="search-console"?e.jsx(cx,{projectName:s.project.name}):null]})}export{Ax as ProjectPage,lx as patchProjectDashboardCache};
|