@canonry/canonry 4.178.4 → 4.179.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/assets/{AuditHistoryPanel-BCtMrEMF.js → AuditHistoryPanel-lD6Q5KaA.js} +1 -1
- package/assets/assets/{BacklinksPage-CIo2hA0i.js → BacklinksPage-ClN1xbOa.js} +1 -1
- package/assets/assets/{ChartPrimitives-B_LDVvTy.js → ChartPrimitives-DG35TyhH.js} +1 -1
- package/assets/assets/{HistoryPage-D24U8cUG.js → HistoryPage-CXKCPfG7.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-BKDdv-jJ.js → MeasurementPropertyPage-CiJsa0If.js} +1 -1
- package/assets/assets/ProjectPage-CD0QbHPd.js +9 -0
- package/assets/assets/{RunRow-B39IK7hK.js → RunRow-DkFcHvDU.js} +1 -1
- package/assets/assets/{RunsPage-R4W1kD0B.js → RunsPage-CLzUDwTj.js} +1 -1
- package/assets/assets/{SettingsPage-BAOGyt1F.js → SettingsPage-0PRgB0gI.js} +1 -1
- package/assets/assets/{SiteHealthSection-Bx7yVNMQ.js → SiteHealthSection-BXAMjVeD.js} +3 -3
- package/assets/assets/{TrafficPage-DL8RvM2R.js → TrafficPage-CP4qsn82.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-COzjakZa.js → TrafficSourceDetailPage-DoaIZ_ix.js} +1 -1
- package/assets/assets/{extract-error-message-B3TERCQ-.js → extract-error-message-Cn74-t3z.js} +1 -1
- package/assets/assets/{index-D0GbiVhZ.css → index-BD8hYPvq.css} +1 -1
- package/assets/assets/{index-xtxQtZRo.js → index-BR9BgNb3.js} +22 -22
- package/assets/assets/{react-sigma_core.esm.min-CbXAujub.js → react-sigma_core.esm.min-CZrBq6qL.js} +1 -1
- package/assets/index.html +2 -2
- package/dist/{chunk-KMK6AOB5.js → chunk-5BZWU35I.js} +145 -54
- package/dist/{chunk-IMEJQQZU.js → chunk-A2AB7UK5.js} +40 -2
- package/dist/{chunk-HNY2FNJH.js → chunk-FFXYNYPZ.js} +2 -2
- package/dist/{chunk-EBRGLDTB.js → chunk-LPUTKQDR.js} +2 -2
- package/dist/{chunk-WYCHM3EP.js → chunk-WG4EDZT3.js} +4 -4
- package/dist/cli.js +5 -5
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-XPAKDZJI.js → intelligence-service-CKGM2RUJ.js} +2 -2
- package/dist/mcp.js +3 -3
- package/package.json +8 -8
- package/assets/assets/ProjectPage-DrIs_ZuR.js +0 -9
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{r as l,j as e,u as Ie,L as os,n as Rs,o as qt,B as Di,C as Ho,h as Wo,k as Yo,D as Xo}from"./vendor-tanstack-Dock0eH1.js";import{M as Ei,I as Xe,T as oe,t as Jo,a as Zo,u as qi,C as el,P as cn,B as P,h as tl,b as sl,c as nl,d as Os,g as Oi,e as Gi,f as de,i as V,j as J,k as ft,l as Me,m as al,n as rl,o as il,p as Fi,q as ol,r as ll,S as Fs,s as cl,v as dl,w as Es,x as Ot,y as ul,z as Sr,A as _i,G as Tt,D as er,E as ml,F as hl,H as xl,J as pl,K as Cr,L as Se,N as gl,O as fl,Q as ha,R as bl,U as yl,V as vl,W as jl,X as Nl,Y as wl,Z as Sl,_ as Cl,$ as kl,a0 as Al,a1 as Pl,a2 as Rl,a3 as Il,a4 as Tl,a5 as $l,a6 as Ui,a7 as Ks,a8 as Ml,a9 as Bi,aa as Qn,ab as Ll,ac as Ye,ad as Dl,ae as El,af as ql,ag as Hn,ah as Ol,ai as Gl,aj as Fl,ak as dn,al as _l,am as Ul,an as Bl,ao as Vi,ap as Ua,aq as Vl,ar as Ki,as as Kl,at as tr,au as zl,av as Ql,aw as Hl,ax as Wl,ay as Yl,az as Xl,aA as Jl,aB as Nn,aC as _s,aD as Zl,aE as ec,aF as tc,aG as sc,aH as zi,aI as nc,aJ as ac,aK as rc,aL as ic,aM as oc,aN as Qi,aO as lc,aP as cc,aQ as dc,aR as uc,aS as mc,aT as hc,aU as xc,aV as pc,aW as gc,aX as fc,aY as bc,aZ as yc,a_ as vc,a$ as jc,b0 as Nc,b1 as wc,b2 as Sc,b3 as Cc,b4 as kc,b5 as Ac,b6 as rs,b7 as Pc,b8 as it,b9 as Rc,ba as Ic,bb as Tc,bc as $c,bd as Mc,be as Lc,bf as Dc,bg as Ec,bh as qc,bi as Oc,bj as Gc,bk as Fc,bl as _c,bm as Uc,bn as Bc,bo as Vc,bp as Kc,bq as zc,br as Qc,bs as Hc,bt as Wc,bu as Yc,bv as Xc,bw as Jc,bx as Zc,by as ed,bz as td,bA as sd,bB as nd,bC as ad,bD as rd,bE as id,bF as od,bG as ld,bH as cd,bI as dd,bJ as ud,bK as md,bL as xa,bM as hd,bN as xd,bO as kr,bP as pd,bQ as gd,bR as fd,bS as bd,bT as yd,bU as vd,bV as jd,bW as Nd,bX as wd,bY as Sd,bZ as Cd,b_ as kd,b$ as Hi,c0 as Ad,c1 as Pd,c2 as Rd,c3 as Id,c4 as Td,c5 as $d,c6 as Md,c7 as Ar,c8 as Ld,c9 as pa,ca as Dd,cb as Ed,cc as qd,cd as Od,ce as Gd,cf as Fd,cg as _d,ch as Wi,ci as Ud,cj as Bd,ck as Vd,cl as Kd,cm as zd,cn as Qd,co as Tn,cp as Hd,cq as Wd,cr as Yd,cs as Pr,ct as Xd}from"./index-BR9BgNb3.js";import{R as Jd}from"./RunRow-DkFcHvDU.js";import{u as Sn,D as rn,a as Us,b as Yi,M as Kn,c as ds,S as Zd}from"./SiteHealthSection-BXAMjVeD.js";import{e as eu,q as Wn,U as tu,r as su,L as nu,s as Xi,i as au,P as Yn,D as Ji,t as ru,u as iu,E as ou,C as Xn,v as lu}from"./vendor-lucide-nYKv-BB7.js";import{C as Jn,f as zs,a as ss,b as Gt,c as $t,d as Wt,e as nt,g as Xt,h as Bs,M as Zi,i as eo,o as xs,j as Ps,p as cu}from"./ChartPrimitives-DG35TyhH.js";import{u as du,a as uu,b as mu,t as hu,e as xu,c as ut}from"./extract-error-message-Cn74-t3z.js";import{R as Qs,C as Hs,a as Zn,X as Ws,Y as Ys,T as Xs,b as Ba,L as ea,A as Cs,d as Gs,e as pu}from"./vendor-recharts-D8rt5lKn.js";import{A as gu}from"./AuditHistoryPanel-lD6Q5KaA.js";import{a as fu,b as bu}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function Vs(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 yu(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=vu(r,1));return a}function vu(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const r=a.getUTCFullYear(),o=String(a.getUTCMonth()+1).padStart(2,"0"),i=String(a.getUTCDate()).padStart(2,"0");return`${r}-${o}-${i}`}function ju(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 Nu(t,s){const n=ju(t,s);return n===null?null:Math.round(n*100)}function ga(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Vs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Vs(t.prior)} ${s})`:`Flat ${n} (${Vs(t.prior)} ${s})`}const to=30;function Rr(t){return Math.round(t*10)/10}function wu(t){return t.prior>=to&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Rr(t.deltaAbs)} vs ${Rr(t.prior)}`}function Su(t,s,n){return t.prior>=to&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Vs(Math.round(t.deltaAbs))} ${s} ${n}`}const Cu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function so(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function no(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 ao(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(so).map(no).filter(Boolean)):new Set}function ro(t,s){const n=so(t).map(no).filter(Boolean).filter(a=>!Cu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function ku(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Au(t,s){const n=ao(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const o of s){if(o.category!=="content"){r.push(o);continue}const i=ro(ku(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function Pu(t){const s=ao(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=ro(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const Ru=1e6;function Iu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/Ru)}const io={queryClass:"all"},Tu=["all","non-brand","branded"];function $u(t){return typeof t=="string"&&Tu.includes(t)}function Mu(t){const s=$u(t.class)?t.class:io.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 Lu(t,s){return s===null||t===null?!1:t!==s}function Du(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===io.queryClass?void 0:t.queryClass}}const Ts=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Ir={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Eu={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},qu="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Ou(t,s){if(s.unavailable)return{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1};if(s.noRun)return{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1};if(t.snapshotsTotal===0)return s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1};if(t.snapshotsWithAnswerText===0)return{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1};if(!s.hasCompetitors)return{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1};const n=t.projectMentionSnapshots+t.competitorMentionSnapshots;return n===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:`${t.score}`,numeric:!0,detail:`${t.projectMentionSnapshots} of ${n} brand mentions`,showRows:!0}}function Gu({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const r=new Map(t.perCompetitor.map(i=>[i.domain,i.mentionSnapshots])),o=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(i=>({label:i,mentions:r.get(i)??0,isYou:!1}))].sort((i,m)=>m.mentions-i.mentions||(i.label<m.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Xe,{text:qu})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const m=i.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${i.isYou?"text-heading font-medium":"text-secondary"}`,children:i.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${i.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${m>0?Math.max(m,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[m.toFixed(1),"%"]})]},i.label)})})]})}function Fu({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",m=!i&&t.branded.snapshotsTotal>0,c=m?a:"non-brand",h=i?"pooled":c,p=c==="branded"?t.branded:t.breakdown,u=c==="branded"?t.breakdown:t.branded,y=Ou(p,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:u.snapshotsTotal>0}),v=h==="non-brand"?Ei[t.tone]:"text-secondary";function b(g){const f=Ts.findIndex(O=>O.value===c);let C=null;g.key==="ArrowRight"||g.key==="ArrowDown"?C=(f+1)%Ts.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?C=(f-1+Ts.length)%Ts.length:g.key==="Home"?C=0:g.key==="End"&&(C=Ts.length-1),C!==null&&(g.preventDefault(),r(Ts[C].value),g.currentTarget.querySelectorAll('[role="radio"]')[C]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:o,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Xe,{text:Eu[h]})]}),m?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:b,children:Ts.map(g=>{const f=g.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>r(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:Ir[h]})]}),y.numeric?e.jsxs("p",{className:`mention-share-value ${v}`,children:[y.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:y.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Ir[h]}),` · ${y.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),y.showRows&&e.jsx(Gu,{breakdown:p,projectLabel:s,competitorDomains:n})]})}function Va({state:t,label:s}){return e.jsx(oe,{tone:Zo(t),children:s??Jo(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"},o=n.length-1,i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((h,p)=>{const u=new Date(h.createdAt).toLocaleDateString();return`${p===o?"Latest run, ":""}${u}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,p)=>{const u=!!(h.model&&p>0&&n[p-1]?.model&&n[p-1].model!==h.model),y=p===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${u?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${y?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,u?"model changed":null,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 Ka(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const o=s.get(r.createdAt);o?o.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:o}])=>({runId:o,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const _u=320;function Uu(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function $r(t,s){return s==="citations"?t.citationState:t.visibilityState==="pending"||t.answerMentioned==null&&t.visibilityState==null?"pending":t.visibilityState==="visible"||t.answerMentioned===!0?"cited":"not-cited"}function Mr(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 Lr(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,o=t[t.length-2].citationState;if(o!=="cited"&&r==="cited")return`Newly ${n}`;if(o==="cited"&&r!=="cited")return"Lost since last run";let i=0;for(let m=t.length-1;m>=0&&t[m].citationState===r;m--)i++;return r==="cited"?i<=1?`${a} in latest run`:`${a} for ${i} runs`:i<=1?`Not ${n} in latest run`:`Not ${n} across ${i} runs`}function Bu(t,s){return t.map(n=>oo(n,s))}function oo(t,s){return s==="citations"?t:{...t,citationState:$r(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:$r(n,s)}))}}function Dr(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,o=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",m=o==="cited"||o==="emerging";return r==="lost"||o!==null&&m&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!m&&i?{key:s,label:`New ${n}`,tone:"positive"}:o===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Vu(t){const s=Ka(Bu(t,"mentions")),n=Ka(t);return[Dr(s,"mentions"),Dr(n,"citations")]}function Ku({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 Er({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Vu(t).map(s=>e.jsx(Ku,{signal:s},s.key))})}function zu({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=qi(),[r,o]=l.useState(new Set),[i,m]=l.useState("mentions"),[c,h]=l.useState(n),p=l.useMemo(()=>{const O=new Map;for(const E of t){const A=E.query,d=s?E.location??null:null,j=s?JSON.stringify([A,d]):A,S=O.get(j)??{key:j,phrase:A,location:d,items:[],rawItems:[]};S.items.push(oo(E,i)),S.rawItems.push(E),O.set(j,S)}return[...O.values()]},[t,i,s]),u=Sn({rows:p,getSearchText:Uu}),y=u.rows.map(O=>O.key),v=y.length>0&&y.every(O=>r.has(O)),b=O=>{o(E=>{const A=new Set(E);return A.has(O)?A.delete(O):A.add(O),A})},g=i==="mentions"?"mentioned":"cited",f=i==="mentions"?"Mention History":"Citation History",C=i==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":i==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:i==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{o(O=>{const E=new Set(O);for(const A of y)v?E.delete(A):E.add(A);return E})},children:v?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),p.length>0?e.jsx(rn,{value:u.query,onChange:u.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:f}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:u.rows.map(({key:O,phrase:E,location:A,items:d,rawItems:j})=>{const S=r.has(O),q=d.map($=>$.citationState),_=q.includes("cited")?"cited":q.includes("emerging")?"emerging":q.includes("lost")?"lost":q.every($=>$==="pending")?"pending":"not-cited",N=Ka(d),T=d.filter($=>$.citationState===el.cited||$.citationState==="emerging").length,F=Lr(N,i);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>b(O),onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),b(O))},tabIndex:0,role:"button","aria-expanded":S,children:[e.jsx("td",{children:e.jsx(eu,{size:14,className:`transition-transform duration-150 text-muted ${S?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:E}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:A??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:d.map($=>e.jsx(cn,{provider:$.provider},$.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Va,{state:_,label:Mr(_,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${T} of ${d.length} engines ${C}`,children:[T,"/",d.length]})]})}),e.jsx("td",{children:e.jsx(Tr,{history:N})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:F}),e.jsx(Er,{items:j})]}),e.jsx("td",{})]}),S&&d.map(($,H)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(cn,{provider:$.provider})}),e.jsx("td",{children:e.jsx(Va,{state:$.citationState,label:Mr($.citationState,i)})}),e.jsx("td",{children:e.jsx(Tr,{history:$.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Lr($.runHistory,i)}),e.jsx(Er,{items:[j[H]??$]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:ve=>{ve.stopPropagation(),a($.id)},children:"View"})})]}),c==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Wu,{item:$,onViewFull:()=>a($.id)})})]})]},$.id))]},O)})})]})}),u.totalRows===0&&u.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Us,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",g==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Qu(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=sl(r);return o.length>=4?[o]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function qr(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function Hu(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 Wu({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}=Hu(t.answerSnippet,_u),o=Qu(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:tl(a,o)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(i=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${qr(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,qr(t,i)?" · competitor source":""]},`c-${i}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(i=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:i},`co-${i}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:i=>{i.stopPropagation(),s()},children:"View full answer →"})]})}function Yu({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,o=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"}),o&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(i=>{const m=a!=null&&a.toLowerCase()===i.domain.toLowerCase(),c=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:c,onClick:r?()=>s(i.domain):void 0,title:r?`Filter answers to queries where ${i.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:i.domain}),e.jsx("td",{children:e.jsx(oe,{tone:nl(i.pressureLabel),children:i.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:i.totalQueries>0?`${i.citationCount} / ${i.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:i.citedQueries.length>0?i.citedQueries.join(", "):"Not cited"}),o&&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 ${i.domain}`,title:`Remove ${i.domain}`,onClick:h=>{h.stopPropagation(),n(i.domain)},children:"Remove"})})]},i.id)})})]})})}function $n({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}function ra({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:o=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:o,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>n(i),children:r?r(i):i},i))})}const fa=nt[0],ba=nt[1],Or=nt[2],Gr=nt[3],Xu=["both","server","ga4"],Fr={fontSize:11,paddingTop:6},_r=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),zt=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function ya(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,o)=>o<t.startIndex||o>t.endIndex?null:t.start+(o-t.startIndex)*a)}function va({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Xe,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function Ju(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,m=o??-1;return!(t[m]!=null&&t[m-1]==null&&t[m+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function Zu({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,m]=l.useState("both"),c=du(t,{sinceMinutes:s,granularity:"day",limit:1}),h=uu(t),u=Ie({...Oi({client:V,path:{name:t}}),enabled:!!t,staleTime:Os}).data?.connected===!0,y=Ie({...Gi({client:V,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&u,staleTime:Os}),v=l.useMemo(()=>c.data?.series?.points??[],[c.data]),b=l.useMemo(()=>{const q=y.data;return new Map((q?.days??[]).map(_=>[_.date,_.sessions]))},[y.data]),g=l.useMemo(()=>{const q=N=>N.measured!==!1;if(v.length===0||q(v[0]))return null;const _=v.findIndex(q)-1;return _<0?{from:v[0].bucket,to:v[v.length-1].bucket}:{from:v[0].bucket,to:v[_].bucket}},[v]),f=c.data?.series?.coverageStart??null,C=c.data?.series?.trends,O=l.useMemo(()=>{const q=ya(C?.crawlerContentHits,v.length),_=ya(C?.aiUserFetchHits,v.length),N=ya(C?.aiReferralLandedHits,v.length);return v.map((T,F)=>({...T,crawlerContentHits:T.measured!==!1?zt(T.crawlerContentHits):null,aiUserFetchHits:T.measured!==!1?zt(T.aiUserFetchHits):null,aiReferralLandedHits:T.measured!==!1?zt(T.aiReferralLandedHits):null,ga4Visits:b.get(T.bucket)??null,crawlTrend:q[F],fetchTrend:_[F],visitTrend:N[F]}))},[v,b,C]),E=c.data?.totals,A=E&&{crawlers:zt(E.crawlerContentHits),fetches:zt(E.aiUserFetchHits),visits:zt(E.aiReferralLandedHits)},d=l.useMemo(()=>v.reduce((q,_)=>({crawlers:q.crawlers+zt(_.crawlerContentHits),fetches:q.fetches+zt(_.aiUserFetchHits),visits:q.visits+zt(_.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[v]),j=A??d,S=j.crawlers>0||j.fetches>0||j.visits>0;if(c.isLoading)return e.jsx(de,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(c.isError)return e.jsxs(de,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!S){const q=h.data?.sources,_=q!==void 0&&q.length===0,N=!_&&f===null;return e.jsxs(de,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:_?"No server-side traffic source connected yet.":N?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:_?"Connect a traffic source to see how AI engines read this site over time.":N?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(de,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(va,{label:"AI crawlers",value:Vs(j.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(va,{label:"AI page fetches",value:Vs(j.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(va,{label:"AI visitors",value:Vs(j.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),v.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:zt(v[v.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:zt(v[v.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:zt(v[v.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:b.get(v[v.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Xe,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:q=>a(q.target.checked),className:"accent-current"}),"Page fetches"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:q=>o(q.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Qs,{width:"100%",height:206,children:e.jsxs(Hs,{data:O,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Zn,{stroke:Jn,vertical:!1}),e.jsx(Ws,{dataKey:"bucket",tick:Gt,stroke:ss,tickFormatter:zs,minTickGap:28}),e.jsx(Ys,{tick:Gt,stroke:ss,width:48,allowDecimals:!1}),e.jsx(Xs,{contentStyle:Wt.contentStyle,labelStyle:Wt.labelStyle,itemStyle:Wt.itemStyle,labelFormatter:$t}),g&&e.jsx(Ba,{x1:g.from,x2:g.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(ea,{wrapperStyle:Fr,iconType:"plainline",iconSize:14,formatter:q=>_r.has(q)?"":q}),e.jsx(Cs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:fa,fill:fa,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Cs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:ba,fill:ba,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Gs,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,stroke:fa,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Gs,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,stroke:ba,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Xe,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(ra,{windows:Xu,value:i,onChange:m,label:"Visit measurement source",formatOption:q=>q==="ga4"?"GA4":q==="both"?"Both":"Server"})]}),e.jsx(Qs,{width:"100%",height:176,children:e.jsxs(Hs,{data:O,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Zn,{stroke:Jn,vertical:!1}),e.jsx(Ws,{dataKey:"bucket",tick:Gt,stroke:ss,tickFormatter:zs,minTickGap:28}),e.jsx(Ys,{tick:Gt,stroke:ss,width:48,allowDecimals:!1}),e.jsx(Xs,{contentStyle:Wt.contentStyle,labelStyle:Wt.labelStyle,itemStyle:Wt.itemStyle,labelFormatter:$t}),g&&e.jsx(Ba,{x1:g.from,x2:g.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(ea,{wrapperStyle:Fr,iconType:"plainline",iconSize:14,formatter:q=>_r.has(q)?"":q}),i!=="ga4"&&e.jsx(Gs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Or,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Gs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Gr,strokeWidth:1.8,strokeDasharray:"5 3",dot:Ju(O.map(q=>q.ga4Visits),Gr)}),r&&i!=="ga4"&&e.jsx(Gs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,stroke:Or,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const em=6,un="__other__",on="_socialTotal";function tm(t,s=em){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const a=[...n.entries()].sort((p,u)=>u[1]!==p[1]?u[1]-p[1]:p[0].localeCompare(u[0])),r=a.slice(0,s),o=new Set(r.map(([p])=>p)),i=Math.max(0,a.length-s),m=new Map;for(const p of t){let u=m.get(p.date);u||(u={date:p.date,[on]:0},m.set(p.date,u));const y=o.has(p.source)?p.source:un;u[y]=(u[y]??0)+p.sessions,u[on]=(u[on]??0)+p.sessions}const c=[...m.values()].sort((p,u)=>String(p.date).localeCompare(String(u.date))),h=r.map(([p])=>p);return i>0&&h.push(un),{data:c,sources:h,otherCount:i}}function ln(t){return t.replace(/\+/g," ")}function lo(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ur="_totalSessions",Br="_organicSessions";function sm(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Ur]:i.sessions,[Br]:i.organicSessions});for(const i of t.days){let m=n.get(i.date);m||(m={[Ur]:0,[Br]:0},n.set(i.date,m));for(const c of i.bySource)m[c.source]=(m[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([i],[m])=>i.localeCompare(m)).map(([i,m])=>({date:i,...m})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const nm=["7d","30d","90d"],am={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ss=nt,za=Xt.textDim,co=Xt.textFaint,pn=25;function rm(t){return Yi(t.landingPage)}const im=25,om=10,ja={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Mn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function uo(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 lm({projectName:t}){const{data:s,isLoading:n,isError:a}=mu(t);if(n)return e.jsx(de,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(de,{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."," ",!J()&&e.jsx(os,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(de,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!J()&&e.jsxs(e.Fragment,{children:[e.jsx(os,{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(de,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:o.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:hu(o.status),children:o.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:o.lastSyncedAt?uo(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:J()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(os,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function cm({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(lm,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(ra,{windows:nm,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Zu,{projectName:t,sinceMinutes:am[s]}),e.jsx(dm,{projectName:t,window:s})]})}function dm({projectName:t,window:s}){const n=Rs(),a=s??"30d",[r,o]=l.useState(null),[i,m]=l.useState(null),[c,h]=l.useState(!0),[p,u]=l.useState(!1),[y,v]=l.useState(!1),[b,g]=l.useState(null),[f,C]=l.useState(null),[O,E]=l.useState("sessions"),[A,d]=l.useState("desc"),[j,S]=l.useState("sessions"),[q,_]=l.useState("desc"),[N,T]=l.useState("sessions"),[F,$]=l.useState("desc"),[H,ve]=l.useState("sessions"),[ue,z]=l.useState("desc"),[ee,re]=l.useState(ja),[W,K]=l.useState([]),[R,se]=l.useState([]),[ce,me]=l.useState(!1);async function X(U){h(!0),g(null);try{const ke=await n.fetchQuery({...Oi({client:V,path:{name:t}}),staleTime:Os});if(U.current)return;if(o(ke),!ke.connected){m(null),re(ja),K([]),se([]),h(!1);return}const fe=a==="all"?void 0:a,pe=await n.fetchQuery({...al({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Os}).then(Jt=>Jt),Lt=pe.windowStart||pe.windowEnd?{...pe.windowStart?{startDate:pe.windowStart}:{},...pe.windowEnd?{endDate:pe.windowEnd}:{}}:void 0,[ct,Pt,Dt]=await Promise.all([n.fetchQuery({...Gi({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Os}).catch(()=>ja),n.fetchQuery({...rl({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Os}).catch(()=>[]),n.fetchQuery({...il({client:V,path:{name:t},query:Lt}),staleTime:Os}).catch(()=>[])]);if(U.current)return;m(pe),re(ct),K(Pt),se(Dt),h(!1)}catch(ke){if(U.current)return;g(ke instanceof Error?ke.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const U={current:!1};return X(U),()=>{U.current=!0}},[t,a,n]);async function Ae(){u(!0),g(null),C(null);try{const U=await Fi(t);C(`Synced ${U.rowCount.toLocaleString()} page rows, ${U.aiReferralCount.toLocaleString()} AI and ${U.socialReferralCount.toLocaleString()} social referral rows (${U.days} days)`),await ft(n,"ga"),await X({current:!1})}catch(U){g(U instanceof Error?U.message:"Sync failed")}finally{u(!1)}}async function B(){v(!0),g(null),C(null);try{await ol(t),await ft(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),m(null),C("GA4 disconnected")}catch(U){g(U instanceof Error?U.message:"Disconnect failed")}finally{v(!1)}}function ae(U){Pe.setPage(1),O===U?d(ke=>ke==="desc"?"asc":"desc"):(E(U),d("desc"))}function Ne(U){j===U?_(ke=>ke==="desc"?"asc":"desc"):(S(U),_("desc"))}function Le(U){N===U?$(ke=>ke==="desc"?"asc":"desc"):(T(U),$("desc"))}const Fe=l.useMemo(()=>i?.topPages?[...i.topPages].sort((U,ke)=>{const fe=U[O],pe=ke[O];return typeof fe=="string"&&typeof pe=="string"?A==="asc"?fe.localeCompare(pe):pe.localeCompare(fe):A==="asc"?fe-pe:pe-fe}):[],[i?.topPages,O,A]),Pe=Sn({rows:Fe,getSearchText:U=>Yi(U.landingPage),pageSize:om}),Qe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((U,ke)=>{const fe=U[j],pe=ke[j];return typeof fe=="string"&&typeof pe=="string"?q==="asc"?fe.localeCompare(pe):pe.localeCompare(fe):q==="asc"?fe-pe:pe-fe}):[],[i?.aiReferrals,j,q]),he=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((U,ke)=>{const fe=U[H],pe=ke[H];return typeof fe=="string"&&typeof pe=="string"?ue==="asc"?fe.localeCompare(pe):pe.localeCompare(fe):ue==="asc"?fe-pe:pe-fe}):[],[i?.aiReferralLandingPages,H,ue]),we=Sn({rows:he,getSearchText:rm,pageSize:im}),Ze=we.totalRows>0?`${we.totalRows.toLocaleString()} ${we.hasQuery?we.totalRows===1?"match":"matches":we.totalRows===1?"row":"rows"}`:we.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function _e(U){we.setPage(1),H===U?z(ke=>ke==="desc"?"asc":"desc"):(ve(U),z("desc"))}const He=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((U,ke)=>{const fe=U[N],pe=ke[N];return typeof fe=="string"&&typeof pe=="string"?F==="asc"?fe.localeCompare(pe):pe.localeCompare(fe):F==="asc"?fe-pe:pe-fe}):[],[i?.socialReferrals,N,F]),{socialChartData:Te,socialChartSources:Ce,socialOtherCount:G}=l.useMemo(()=>{const U=tm(R);return{socialChartData:U.data,socialChartSources:U.sources,socialOtherCount:U.otherCount}},[R]),{chartData:M,chartSources:L,dateRange:je}=l.useMemo(()=>{const U=sm(ee,W);return{chartData:U.data,chartSources:U.sources,dateRange:U.dateRange}},[ee,W]);if(c&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return J()?e.jsx(de,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(um,{projectName:t,onConnected:()=>{(async()=>(await ft(n,"ga"),await X({current:!1})))()}});const qe=i?.organicSharePctDisplay??"0%",Y=i?.channelBreakdown?.organic.sharePctDisplay??qe,Be=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,mt=i?.aiSessionsDeduped??0,ot=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,De=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Oe=i?.paidAiSessionsBySession??0,xt=i?.paidAiSharePctBySessionDisplay??"0%",We=i?new Set(i.aiReferrals.map(U=>U.source.toLowerCase())).size:0,Ve=Qe[0]??null,$e=i?.totalDirectSessions??0,jt=i?.directSharePctDisplay??"0%",Mt=i?.channelBreakdown?.direct.sessions??$e,Ue=i?.channelBreakdown?.direct.sharePctDisplay??jt,Ge=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,bt=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ke=i?.socialSessions??0,Nt=i?.socialSharePctDisplay??"0%",kt=i?.channelBreakdown?.social.sessions??Ke,yt=i?.channelBreakdown?.social.sharePctDisplay??Nt,At=i?new Set(i.socialReferrals.map(U=>U.source.toLowerCase())).size:0,lt=He[0]??null;return e.jsxs(e.Fragment,{children:[b&&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:b}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:f}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!J()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:p,onClick:Me(Ae),children:[e.jsx(Wn,{className:`w-3.5 h-3.5 mr-1.5 ${p?"animate-spin":""}`}),p?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:y,onClick:Me(B),children:[e.jsx(tu,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Xe,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Na,{value:Mn(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Na,{value:Mn(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${qe} of total`,tone:"positive"}),e.jsx(Na,{value:i.totalUsers===null?"—":Mn(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!J()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:p,onClick:Me(Ae),children:[e.jsx(Wn,{className:`w-3.5 h-3.5 mr-1.5 ${p?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Xe,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),je&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(je.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(je.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),M.length>0&&e.jsxs(de,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:L.length>0?"AI vs. total sessions":"All sessions (baseline)"}),L.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),L.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Qs,{width:"100%",height:"100%",children:e.jsxs(Hs,{data:M,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Ws,{dataKey:"date",tick:Gt,tickLine:!1,axisLine:{stroke:ss},tickFormatter:zs}),e.jsx(Ys,{tick:Gt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Xs,{...Wt,labelFormatter:$t,formatter:(U,ke)=>{const fe=typeof U=="number"?U.toLocaleString():String(U??0),pe=String(ke??"");return pe==="_totalSessions"?[fe,"Total Sessions"]:pe==="_organicSessions"?[fe,"Organic Sessions"]:[fe,pe]}}),e.jsx(ea,{wrapperStyle:{fontSize:11,color:Xt.text},formatter:U=>U==="_totalSessions"?"Total Sessions":U==="_organicSessions"?"Organic Sessions":U}),e.jsx(Cs,{type:"monotone",dataKey:"_totalSessions",stroke:Xt.textFaint,fill:Xt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),L.map((U,ke)=>e.jsx(Cs,{type:"monotone",dataKey:U,stackId:"ai",stroke:Ss[ke%Ss.length],fill:Ss[ke%Ss.length],fillOpacity:.4,strokeWidth:1.5},U))]})})})]}),e.jsxs(de,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(ts,{label:"Organic",value:Y,hint:`${Be.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(ts,{label:"Social",value:yt,hint:`${kt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(ts,{label:"Direct",value:Ue,hint:`${Mt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(ts,{label:"Visitors from AI (at least)",value:De,hint:Oe>0?`${ot.toLocaleString()} sessions · ${Oe.toLocaleString()} paid`:`${ot.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(ts,{label:"Other channels",value:bt,hint:`${Ge.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),Ve&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:Ve.source})," via ",Ve.medium,", accounting for ",Ve.sessions.toLocaleString()," sessions.",Oe>0&&e.jsxs("span",{children:[" Paid AI: ",Oe.toLocaleString()," sessions (",xt,")."]})]})]}),e.jsxs(de,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${We} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Bt,{label:"Source",sortKey:"source",current:j,dir:q,onSort:Ne,align:"left"}),e.jsx(Bt,{label:"Medium",sortKey:"medium",current:j,dir:q,onSort:Ne,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Bt,{label:"Sessions",sortKey:"sessions",current:j,dir:q,onSort:Ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Qe.map(U=>e.jsx(hm,{referral:U,totalSessions:mt},`${U.source}:${U.medium}:${U.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(de,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:Ze})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(rn,{value:we.query,onChange:we.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),we.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Bt,{label:"Landing Page",sortKey:"landingPage",current:H,dir:ue,onSort:_e,align:"left"}),e.jsx(Bt,{label:"Source",sortKey:"source",current:H,dir:ue,onSort:_e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Bt,{label:"Sessions",sortKey:"sessions",current:H,dir:ue,onSort:_e,align:"right"})]})}),e.jsx("tbody",{children:we.rows.map(U=>e.jsx(xm,{row:U},`${U.landingPage}:${U.source}:${U.medium}:${U.sourceDimension}`))})]})}),e.jsx(Us,{page:we.page,pageSize:we.pageSize,visibleRows:we.rows.length,totalRows:we.totalRows,onPageChange:we.setPage,itemLabel:we.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>we.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Xe,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(de,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ts,{label:"Social Sessions",value:Mn(Ke),hint:`${Ke.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(ts,{label:"Share of Traffic",value:Nt,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(ts,{label:"Platforms",value:String(At),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),lt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${lt.source} via ${lt.medium}`,children:lo(ln(lt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:lt.medium,children:["via ",ln(lt.medium)," · ",lt.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ts,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(ts,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(ts,{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."})]})]})]}),Te.length>0&&e.jsxs(de,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),G>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ce.length-1," sources · ",G," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Qs,{width:"100%",height:"100%",children:e.jsxs(Hs,{data:Te,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Ws,{dataKey:"date",tick:Gt,tickLine:!1,axisLine:{stroke:ss},tickFormatter:zs}),e.jsx(Ys,{tick:Gt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Xs,{...Wt,labelFormatter:$t,formatter:(U,ke)=>{const fe=typeof U=="number"?U.toLocaleString():String(U??0),pe=String(ke??"");if(pe===on)return[fe,"Total Social"];if(pe===un){const Lt=`Other (${G} source${G===1?"":"s"})`;return[fe,Lt]}return[fe,ln(pe)]}}),e.jsx(Cs,{type:"monotone",dataKey:on,stroke:co,fill:Xt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ce.map((U,ke)=>{const pe=U===un?za:Ss[ke%Ss.length];return e.jsx(Cs,{type:"monotone",dataKey:U,stackId:"social",stroke:pe,fill:pe,fillOpacity:.4,strokeWidth:1.5},U)})]})})}),e.jsx(gm,{sources:Ce,otherCount:G})]}),e.jsxs(de,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?He.length>pn&&!ce?`Top ${pn} of ${He.length}`:`${He.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Bt,{label:"Source",sortKey:"source",current:N,dir:F,onSort:Le,align:"left"}),e.jsx(Bt,{label:"Medium",sortKey:"medium",current:N,dir:F,onSort:Le,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Bt,{label:"Sessions",sortKey:"sessions",current:N,dir:F,onSort:Le,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Bt,{label:"Users",sortKey:"users",current:N,dir:F,onSort:Le,align:"right"})]})}),e.jsx("tbody",{children:(ce?He:He.slice(0,pn)).map(U=>e.jsx(pm,{referral:U,totalSessions:Ke},`${U.source}:${U.medium}:${U.channelGroup}`))})]})}),He.length>pn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>me(U=>!U),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:ce?`Show top ${pn}`:`Show all ${He.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Xe,{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(rn,{value:Pe.query,onChange:Pe.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Bt,{label:"Landing Page",sortKey:"landingPage",current:O,dir:A,onSort:ae,align:"left"}),e.jsx(Bt,{label:"Sessions",sortKey:"sessions",current:O,dir:A,onSort:ae,align:"right"}),e.jsx(Bt,{label:"Organic",sortKey:"organicSessions",current:O,dir:A,onSort:ae,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Pe.rows.map(U=>e.jsx(mm,{page:U},U.landingPage))})]})}),Pe.totalRows===0&&Pe.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Us,{page:Pe.page,pageSize:Pe.pageSize,visibleRows:Pe.rows.length,totalRows:Pe.totalRows,onPageChange:Pe.setPage,itemLabel:Pe.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${uo(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function um({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,m]=l.useState(null),[c,h]=l.useState(!1),[p,u]=l.useState(null),y=l.useRef(null),v=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),o(f.name);const C=new FileReader;C.onload=()=>{const O=C.result;try{const E=JSON.parse(O);if(!E.client_email||!E.private_key){u("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),m(null);return}m(O)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},C.onerror=()=>{u("Failed to read file."),m(null)},C.readAsText(f)},[]);async function b(){if(u(null),!n.trim()){u("Property ID is required.");return}if(!i){u("Please upload a service account key file.");return}h(!0);try{await ll(t,{propertyId:n.trim(),keyJson:i});try{await Fi(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(de,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),p&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:p}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:g=>a(g.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:y,type:"file",accept:".json,application/json",onChange:v,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(su,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(P,{variant:"default",size:"sm",disabled:c||!n.trim()||!i,onClick:Me(b),children:c?"Connecting & syncing…":"Connect GA4"})]})}function Bt({label:t,sortKey:s,current:n,dir:a,onSort:r,align:o}){const i=n===s;return e.jsx("th",{className:`py-1 ${o==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${i?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,i&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const mo={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Na({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 ${mo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function ts({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(Xe,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${mo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function mm({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 ho={session:"Session",first_user:"First Visit",manual_utm:"UTM"},xo={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 hm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=ho[t.sourceDimension]??t.sourceDimension,r=xo[t.sourceDimension]??"",o=t.trafficClass==="paid"?"Paid":"Organic",i=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:i,children:o})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function xm({row:t}){const s=ho[t.sourceDimension]??t.sourceDimension,n=xo[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(Kn,{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 pm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=ln(t.source),o=ln(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:o}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function gm({sources:t,otherCount:s}){const n=[{key:on,color:co,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===un)n.push({key:un,color:za,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=ln(r);n.push({key:r,color:Ss[a%Ss.length]??za,label:lo(o,32),tooltip:o})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function fm(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 bm=["7d","30d","90d","all"],Ln=500,Vr=[{key:"clicks",label:"Clicks",color:nt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:nt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Bs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],js=25,ym="canonry:google-oauth-complete",vm=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function jm(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const c=t.prior[s],h=t.trailing[s];return c!==null&&h!==null&&c<=0&&h>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(r===0)return`→ no change vs prior ${a}d`;const o=Math.abs(r*100),i=o<.1?"<0.1%":`${vm.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function Kr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function zr(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 Qr(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Nm({projectName:t,refreshNonce:s}){const n=Rs(),[a,r]=l.useState(!1),[o,i]=l.useState([]),[m,c]=l.useState([]),[h,p]=l.useState([]),[u,y]=l.useState(null),[v,b]=l.useState([]),[g,f]=l.useState([]),[C,O]=l.useState(null),[E,A]=l.useState(""),[d,j]=l.useState(""),[S,q]=l.useState("30"),[_,N]=l.useState(!1),[T,F]=l.useState("30d"),[$,H]=l.useState(["clicks","impressions"]),[ve,ue]=l.useState(!0),[z,ee]=l.useState(null),[re,W]=l.useState(0),[K,R]=l.useState({startDate:"",endDate:"",query:"",page:""}),[se,ce]=l.useState(0),[me,X]=l.useState(!1),[Ae,B]=l.useState(0),[ae,Ne]=l.useState(!1),[Le,Fe]=l.useState(""),[Pe,Qe]=l.useState(!0),[he,we]=l.useState(!1),[Ze,_e]=l.useState(!1),[He,Te]=l.useState(!1),[Ce,G]=l.useState(!1),[M,L]=l.useState(!1),[je,qe]=l.useState(!1),[Y,Be]=l.useState(null),[mt,ot]=l.useState(!1),[De,Oe]=l.useState(!1),[xt,We]=l.useState(null),[Ve,$e]=l.useState(null),[jt,Mt]=l.useState([]),[Ue,Ge]=l.useState(new Set),[bt,Ke]=l.useState({}),[Nt,kt]=l.useState(new Set),[yt,At]=l.useState(""),[lt,U]=l.useState(null),[ke,fe]=l.useState(""),[pe,Lt]=l.useState(!1),[ct,Pt]=l.useState(!1),[Dt,Jt]=l.useState(!1),[Et,ls]=l.useState(!1),[at,ps]=l.useState("indexed"),[wt,gs]=l.useState(null),Ft=!!(K.query.trim()||K.page.trim()||wt),Zt=wt!==null,Vt=l.useMemo(()=>{if(!wt)return h;const{key:x,dir:D}=wt;return[...h].sort((Z,le)=>{const ze=x===Fs.CTR?Number.isFinite(Z.ctr)?Z.ctr:0:Z[x],Je=x===Fs.CTR?Number.isFinite(le.ctr)?le.ctr:0:le[x];return D==="asc"?ze-Je:Je-ze})},[h,wt]),et=Sn({rows:Vt,pageSize:ds}),fs=ae?et.rows:Vt,_t=Sn({rows:(xt??[]).filter(x=>x.path.toLowerCase().includes(yt.trim().toLowerCase())),pageSize:ds}),[St,bs]=l.useState([]),[dt,ns]=l.useState(null),[k,be]=l.useState(1),ye=l.useMemo(()=>{if(St.length<2)return null;const x=St[St.length-1],D=St[St.length-2];return{indexed:x.indexed-D.indexed,notIndexed:x.notIndexed-D.notIndexed}},[St]);l.useEffect(()=>{be(1)},[Y,at,dt]);const I=l.useMemo(()=>dt?(Y?.reasonGroups??[]).find(x=>x.reason===dt):void 0,[Y,dt]),Q=l.useMemo(()=>Y?at==="indexed"?Y.indexed:at==="deindexed"?Y.deindexed:at==="notIndexed"?dt?I?.urls??[]:(Y.reasonGroups??[]).length===0?Y.notIndexed:[]:[]:[],[Y,at,dt,I]),xe=Math.max(1,Math.ceil(Q.length/js)),te=Math.min(Math.max(1,k),xe),ne=(te-1)*js,Ee=l.useMemo(()=>Y?.indexed.slice(ne,ne+js)??[],[Y,ne]),as=l.useMemo(()=>Y?.notIndexed.slice(ne,ne+js)??[],[Y,ne]),pt=l.useMemo(()=>Y?.deindexed.slice(ne,ne+js)??[],[Y,ne]),Js=l.useMemo(()=>(I?.urls??[]).slice(ne,ne+js),[I,ne]),[w,ie]=l.useState(!1),[rt,Re]=l.useState(null),[gt,cs]=l.useState(null),[Kt,es]=l.useState(null);function Oo(x,D){const Z=xu(x),le=fm(Z);le?(cs(le),Re(null)):(cs(null),Re(Z.message||D))}const Ut=o.find(x=>x.connectionType==="gsc"),Is=(Ut?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),oa=jt.length>0?jt:(xt??[]).map(x=>x.path),hr=oa.filter(x=>xt?.some(D=>D.path===x&&D.isSitemapsIndex)).length,Go=hr===1?"Resubmit sitemap index":hr>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Fo=h.length>0||v.length>0||g.length>0,la=cl(),ca=dl();async function xr(x,D=!1){if(!x){c([]),A("");return}_e(!0);try{const{sites:Z}=await n.fetchQuery({...Sl({client:V,path:{name:t}}),staleTime:D?0:Tt});c(Z),A(x.propertyId??Z[0]?.siteUrl??""),cs(null)}catch(Z){c([]),Oo(Z,"Failed to load Search Console properties")}finally{_e(!1)}}async function hn(x){G(!0);const D=x??se;try{const Z=Ft?Ln:ds,le=Ft?0:D,ze={limit:String(Z)};K.startDate&&(ze.startDate=K.startDate),K.endDate&&(ze.endDate=K.endDate),K.query&&(ze.query=K.query),K.page&&(ze.page=K.page),le>0&&(ze.offset=String(le)),T&&T!=="all"&&!K.startDate&&(ze.window=T);const Je=await n.fetchQuery({...hl({client:V,path:{name:t},query:ze}),staleTime:Tt}),tt=Je.rows;Ft?(X(!1),p(tt),B(tt.length),Ne(!0)):(X(le+tt.length<Je.totalMatching),p(tt),B(0),Ne(!1))}catch(Z){p([]),X(!1),B(0),Re(Z instanceof Error?Z.message:"Failed to load GSC performance data")}finally{G(!1)}}async function da(){try{const x={};K.startDate&&(x.startDate=K.startDate),K.endDate&&(x.endDate=K.endDate),T&&T!=="all"&&!K.startDate&&(x.window=T);const D=await n.fetchQuery({...ml({client:V,path:{name:t},query:x}),staleTime:Tt});y(D)}catch{y(null)}}async function Rn(x=!1){L(!0);try{const D=Le.trim()||void 0,Z={limit:"20"};D&&(Z.url=D);const[le,ze]=await Promise.all([n.fetchQuery({...Nl({client:V,path:{name:t},query:Z}),staleTime:x?0:Tt}),n.fetchQuery({...wl({client:V,path:{name:t}}),staleTime:x?0:Tt})]);b(le),f(ze)}catch(D){b([]),f([]),Re(D instanceof Error?D.message:"Failed to load GSC inspection history")}finally{L(!1)}}async function pr(x=!1){ot(!0);try{const[D,Z]=await Promise.all([n.fetchQuery({...gl({client:V,path:{name:t}}),staleTime:x?0:Tt}),n.fetchQuery({...fl({client:V,path:{name:t}}),staleTime:x?0:Tt}).catch(()=>[])]);Be(D),bs(Z)}catch(D){Be(null),bs([]),Re(D instanceof Error?D.message:"Failed to load coverage data")}finally{ot(!1)}}async function gr(x){ie(!0),Re(null);try{const D=await Cr(t,{urls:x}),{succeeded:Z,failed:le,total:ze}=D.summary;Se({title:"Indexing requested",detail:le===0?`${Z} URL${Z!==1?"s":""} submitted for indexing.`:`${Z}/${ze} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to request indexing")}finally{ie(!1)}}async function _o(){ie(!0),Re(null);try{const x=await Cr(t,{urls:[],allUnindexed:!0}),{succeeded:D,failed:Z,total:le}=x.summary;Se({title:"Indexing requested",detail:Z===0?`${D} unindexed URL${D!==1?"s":""} submitted for indexing.`:`${D}/${le} submitted successfully, ${Z} failed.`,tone:Z===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(x){Re(x instanceof Error?x.message:"Failed to request indexing")}finally{ie(!1)}}async function ua(){Oe(!0),Re(null);try{const x=await ha(t);n.setQueryData(bl({client:V,path:{name:t}}),x),We(x.sitemaps),$e(x.summary),Mt(x.preferredSubmissionUrls),Ge(new Set),Ke({}),x.sitemaps.length===0&&es("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(x){Re(x instanceof Error?x.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function Uo(x){const D=Ue.has(x);if(Ge(Z=>{const le=new Set(Z);return D?le.delete(x):le.add(x),le}),!(D||bt[x])){kt(Z=>new Set(Z).add(x));try{const Z=await ha(t,x);Ke(le=>({...le,[x]:Z.sitemaps}))}catch(Z){Re(Z instanceof Error?Z.message:"Failed to load sitemap files")}finally{kt(Z=>{const le=new Set(Z);return le.delete(x),le})}}}async function Zs(x){if(!Is||x.length===0)return;const D=[...new Set(x)];Pt(!0),Re(null),U({completed:0,total:D.length});let Z=0,le=0,ze=0,Je=null;try{for(let vt=0;vt<D.length;vt+=50){const st=D.slice(vt,vt+50);try{const ge=await yl(t,st);Z+=ge.summary.accepted,le+=ge.summary.failed,ze+=st.length,U({completed:ze,total:D.length})}catch(ge){ze+=st.length;const ys=st.length,xn=D.length-ze,In=ge instanceof Error?ge.message:"The batch request failed",vs=`${Z} accepted, ${le} failed, ${ys} unconfirmed, ${xn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Je=`Sitemap submission stopped after a batch request failed. ${vs} ${In}`,Re(Je),Se({title:"Sitemap resubmission partially completed",detail:vs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const tt=D.length;Se({title:le===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:le===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${Z}/${tt} sitemap submissions; ${le} failed. Indexing is not guaranteed.`,tone:le===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),fe("")}catch(tt){Re(tt instanceof Error?tt.message:"Failed to submit sitemap to Google")}finally{Pt(!1),U(null),await ua(),Je&&Re(Je)}}async function Bo(){Pt(!0);const x=xt??[];try{const D=x.filter(le=>le.isSitemapsIndex),Z=[];for(let le=0;le<D.length;le+=4)(await Promise.all(D.slice(le,le+4).map(async Je=>{const tt=bt[Je.path];if(tt)return tt;const vt=await ha(t,Je.path);return Ke(st=>({...st,[Je.path]:vt.sitemaps})),vt.sitemaps}))).forEach((Je,tt)=>{Z.push(...Je.length>0?Je.map(vt=>vt.path):[D[le+tt].path])});await Zs([...x.filter(le=>!le.isSitemapsIndex).map(le=>le.path),...Z])}catch(D){Re(D instanceof Error?D.message:"Failed to load sitemap files"),Pt(!1)}}async function fr(x){Lt(!0),Re(null);try{await vl(t,"gsc",x),await ft(n,"google"),i(D=>D.map(Z=>Z.connectionType==="gsc"?{...Z,sitemapUrl:x}:Z)),Se({title:"Default sitemap updated",detail:x,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to set the default sitemap")}finally{Lt(!1)}}async function br(x){try{await ca.mutateAsync({projectName:t,projectLabel:t,opts:x?{sitemapUrl:x}:void 0})}catch{}}async function yr(){Qe(!0),Re(null);try{const[x,D]=await Promise.all([_i().catch(()=>null),n.fetchQuery({...er({client:V,path:{name:t}}),staleTime:Tt}).catch(()=>[])]);r(!!x?.google?.configured),i(D);const Z=D.find(le=>le.connectionType==="gsc");await Promise.all([xr(Z),hn(),da(),Rn(),pr(),Z?.propertyId?ua():Promise.resolve()])}finally{Qe(!1)}}l.useEffect(()=>{yr()},[t,s]),l.useEffect(()=>{ce(0),ee(null),R(x=>x.startDate||x.endDate?{...x,startDate:"",endDate:""}:x),W(x=>x+1),da()},[T]);const vr=l.useRef(!1);l.useEffect(()=>{if(!vr.current){vr.current=!0;return}ce(0),et.setPage(1),hn(0)},[re]);function ma(x){const D=z===x?null:x;ee(D),R(Z=>({...Z,startDate:D??"",endDate:D??""})),W(Z=>Z+1)}const jr=l.useRef(!1);l.useEffect(()=>{if(!jr.current){jr.current=!0;return}ce(0),hn(0)},[Zt]);async function Nr(){if(!a){Re("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),Re(null),es(null);try{let x=function(ge){if(ge.source!==le||ge.origin!==ze||!ge.data||typeof ge.data!="object")return;const ys=ge.data;ys.type!==ym||ys.connectionType!=="gsc"||st(!0)};const{authUrl:D,redirectUri:Z}=await pl(t,"gsc");if(!D.startsWith("https://accounts.google.com/")){Re("Unexpected OAuth redirect URL. Please try again.");return}const le=window.open(D,"_blank","width=600,height=700");if(!le){window.location.assign(D);return}const ze=Z?new URL(Z).origin:window.location.origin;let Je=!1,tt=null;const vt=()=>{tt!==null&&window.clearInterval(tt),window.removeEventListener("message",x)},st=async ge=>{if(!Je){Je=!0,vt(),es(ge?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await ft(n,"google"),await yr()}finally{es(null)}}};window.addEventListener("message",x),es("Finish the Google consent flow in the popup. This page will refresh automatically."),tt=window.setInterval(()=>{le.closed&&st(!1)},1e3)}catch(x){Re(x instanceof Error?x.message:"Failed to start OAuth flow")}finally{we(!1)}}async function Vo(){Re(null),es(null);try{await xl(t,"gsc"),await ft(n,"google"),i(x=>x.filter(D=>D.connectionType!=="gsc")),c([]),A("")}catch(x){Re(x instanceof Error?x.message:"Failed to disconnect")}}async function Ko(){if(E){Te(!0),Re(null);try{await Cl(t,"gsc",E),await ft(n,"google"),i(x=>x.map(D=>D.connectionType==="gsc"?{...D,propertyId:E}:D)),Se({title:"GSC property updated",detail:`${t} is now linked to ${E}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(x){Re(x instanceof Error?x.message:"Failed to save GSC property")}finally{Te(!1)}}}async function zo(){Re(null),es(null);try{await la.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:_||void 0}}),await ft(n,"gsc")}catch{}}async function wr(){if(d.trim()){qe(!0),Re(null),es(null);try{const x=await jl(t,d.trim());await ft(n,"gsc"),O(x),j(""),await Rn()}catch(x){Re(x instanceof Error?x.message:"Failed to inspect URL")}finally{qe(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),gt&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:gt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:gt.message}),(Es(gt.enableUrl)||Es(gt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Es(gt.enableUrl)&&e.jsx("a",{href:Es(gt.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Es(gt.indexingApiUrl)&&e.jsx("a",{href:Es(gt.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>cs(null),children:"×"})]})}),rt&&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:[rt,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Re(null),children:"×"})]}),Kt&&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:[Kt,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>es(null),children:"×"})]}),Pe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ut?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:Ut.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",Y?.lastInspectedAt?Ot(Y.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Me(Vo),children:"Disconnect"})]}):e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:he,onClick:Me(Nr),children:he?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(os,{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."})]})]})]}),(Ut||Fo)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(de,{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(Xe,{text:`Tile percentages compare the trailing half of the selected window with the prior equal-length half. The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${Ln.toLocaleString()} matching rows while the table shows ${ds} per page.`})]}),u?.window?.startDate&&u.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[u.window.startDate," to ",u.window.endDate,(u.window.daysSinceLatestData??0)>0&&` · latest data ${u.window.daysSinceLatestData} day${u.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ra,{windows:bm,value:T,onChange:x=>{F(x),ce(0),et.setPage(1)},label:"Search Console time period",formatOption:x=>x==="all"?"All":x}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Ce,onClick:()=>{ce(0),et.setPage(1),hn(0),da()},children:Ce?"Loading…":"Apply filters"})]})]}),u&&u.daily.length>0&&(()=>{const{totals:x,daily:D,trends:Z,periodComparison:le}=u,Je=Vr.filter(ge=>$.includes(ge.key)).map(ge=>({dataKey:ge.key,label:ge.label,color:ge.color,axisId:ge.key,inverted:ge.inverted,formatValue:ge.format,trend:ve?Z?.[ge.key]??null:null})),tt=ge=>x[ge]??null,vt=new Map(D.map(ge=>[ge.date,ge])),st=D.length===0?[]:yu(D[0].date,D[D.length-1].date).map(ge=>vt.get(ge)??{date:ge});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Vr.map(ge=>{const ys=$.includes(ge.key),xn=tt(ge.key),In=xn===null;return e.jsxs("button",{type:"button","aria-pressed":ys,disabled:In,className:`rounded-md border px-3 py-2 text-left transition-colors ${ys?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${In?"cursor-not-allowed opacity-50":""}`,onClick:()=>{H(vs=>vs.includes(ge.key)?vs.length===1?vs:vs.filter(Qo=>Qo!==ge.key):[...vs,ge.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:ys?ge.color:"transparent",border:`1px solid ${ge.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ge.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:xn===null?"—":ge.format(xn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:jm(le,ge.key,ge.inverted)})]},ge.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:ve,onChange:ge=>ue(ge.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Zi,{data:st,xKey:"date",series:Je,xTickFormatter:zs,labelFormatter:$t,onSelectX:ma,selectedX:z})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:D.map(ge=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":z===ge.date,onClick:()=>ma(ge.date),children:[$t(ge.date),": ",ge.clicks," clicks, ",ge.impressions," impressions"]},ge.date))}),z&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",$t(z)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ma(z),children:["Show all ",x.days," days"]})]}),x.position!==null&&(x.positionDays??x.days)<x.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",x.positionDays," of ",x.days," days. The rest have no property-level position recorded."]}),(x.position===null||x.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:K.startDate,onChange:x=>R(D=>({...D,startDate:x.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:K.endDate,onChange:x=>R(D=>({...D,endDate:x.target.value}))}),e.jsx(rn,{value:K.query,onChange:x=>R(D=>({...D,query:x})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(rn,{value:K.page,onChange:x=>R(D=>({...D,page:x})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(Fs).map(x=>e.jsx("th",{className:"text-right","aria-sort":wt?.key===x?wt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{et.setPage(1),gs(D=>D?.key===x?D.dir==="desc"?{key:x,dir:"asc"}:null:{key:x,dir:"desc"})},children:[ul[x],wt?.key===x?wt.dir==="desc"?" ↓":" ↑":""]})},x))]})}),e.jsx("tbody",{children:fs.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:x.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Kn,{value:x.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(x.ctr)?x.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.position.toFixed(1)})]},`${x.date}:${x.query}:${x.page}:${D}`))})]})}),e.jsx(Us,{page:ae?et.page:Math.floor(se/ds)+1,pageSize:ds,visibleRows:fs.length,totalRows:ae?Ae:void 0,hasNextPage:ae?void 0:me,disabled:Ce,itemLabel:ae?"matches":"rows",onPageChange:x=>{if(ae){et.setPage(x);return}const D=(x-1)*ds;ce(D),hn(D)}}),ae&&Ae>=Ln?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Ln.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(de,{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(Xe,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Y&&Y.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:w,onClick:()=>{_o()},children:w?"Requesting…":`Request indexing (${Y.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:mt,onClick:()=>{pr(!0)},children:mt?"Loading…":"Reload saved coverage"})]})]}),Y&&Y.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const x=Y.summary.indexed+Y.summary.notIndexed,D=x>0?Y.summary.indexed/x:0,Z=x>0?Y.summary.notIndexed/x:0,le=54,ze=2*Math.PI*le,Je=ze*(1-D),tt=ze*Z,vt=ze*D;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:le,fill:"none",stroke:Xt.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:le,fill:"none",stroke:Bs.positiveDeep,strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Je,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),Y.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:le,fill:"none",stroke:Xt.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${ze-tt}`,strokeDashoffset:-vt,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(D*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(Y.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(Y.reasonGroups??[]).length," ",(Y.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),Y.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(x=>{const D=x==="indexed"?Y.indexed.length:x==="notIndexed"?Y.notIndexed.length:Y.deindexed.length,Z=x==="indexed"?"Indexed":x==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":at===x,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${at===x?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{ps(x),ns(null)},children:[Z," (",D,")"]},x)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[at==="indexed"&&Y.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:Ee.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.crawlTime?x.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.isMobileFriendly===!0?"Yes":x.isMobileFriendly===!1?"No":"—"})]},x.id))})]}),at==="notIndexed"&&!dt&&(Y.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(Y.reasonGroups??[]).map(x=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>ns(x.reason),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),ns(x.reason))},tabIndex:0,role:"button","aria-label":`View ${x.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:x.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.count})]},x.reason))})]}),at==="notIndexed"&&!dt&&(Y.reasonGroups??[]).length===0&&Y.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:as.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"})]},x.id))})]}),at==="notIndexed"&&dt&&(()=>{const x=(Y.reasonGroups??[]).find(D=>D.reason===dt);return x?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>ns(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:x.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[x.count," affected page",x.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:w,onClick:()=>{gr(x.urls.map(D=>D.url))},children:w?"Requesting…":`Request indexing (${x.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Js.map(D=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:D.url}),e.jsx("td",{className:"text-secondary",children:D.crawlTime?D.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:w,onClick:()=>{gr([D.url])},title:"Request indexing",children:"Index"})})]},D.id))})]})]}):null})(),at==="deindexed"&&Y.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:pt.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState}),e.jsx("td",{className:"text-secondary",children:x.currentState}),e.jsx("td",{className:"text-secondary",children:x.transitionDate.split("T")[0]})]},`${x.url}-${D}`))})]}),(at==="indexed"&&Y.indexed.length===0||at==="notIndexed"&&!dt&&Y.notIndexed.length===0||at==="deindexed"&&Y.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Us,{page:te,pageSize:js,visibleRows:Math.min(js,Q.length-ne),totalRows:Q.length,onPageChange:be,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Et,onClick:()=>ls(x=>!x),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Et?"Hide snapshots":St.length>0?`View ${St.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",Y.summary.indexed.toLocaleString()," indexed, ",Y.summary.notIndexed.toLocaleString()," not indexed.",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."]})]}),Et&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:St.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:St.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.notIndexed.toLocaleString()})]},x.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:mt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(de,{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(Xe,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:De||!Ut?.propertyId,onClick:()=>{ua()},children:De?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:ke,onChange:x=>fe(x.target.value),onKeyDown:x=>x.key==="Enter"&&void Zs([ke.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!Is||ct||!ke.trim(),onClick:()=>{Zs([ke.trim()])},children:ct?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Is||ct||oa.length===0,onClick:()=>{Zs(oa)},children:ct?"Resubmitting…":Go}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Is||ct||!xt?.length,onClick:()=>{Bo()},children:"Resubmit all files"}),Ve&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ve.indexes," index",Ve.indexes===1?"":"es",", ",Ve.files," file",Ve.files===1?"":"s"]}),lt&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",lt.completed,"/",lt.total]})]}),!Is&&Ut&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Me(Nr),children:"Reconnect"})]}),xt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:xt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(rn,{value:yt,onChange:x=>{At(x),_t.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:_t.rows.flatMap(x=>{const D=Kr(x),Z=zr(x),le=Qr(x),ze=bt[x.path]??[],Je=Ue.has(x.path),tt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Kn,{value:x.path})}),e.jsx("td",{className:"text-secondary",children:x.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Je,"aria-label":`${Je?"Collapse":"Expand"} files in ${x.path}`,onClick:()=>{Uo(x.path)},children:Nt.has(x.path)?"Loading…":`${Je?"▾":"▸"} Index${bt[x.path]?` (${ze.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:le}),e.jsx("td",{className:"text-secondary",children:x.lastSubmitted?x.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.lastDownloaded?x.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:D.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:Z||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!Is||ct,onClick:()=>{Zs([x.path])},children:x.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Ut?.sitemapUrl===x.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:pe,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{fr(x.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:ca.isPending,onClick:()=>{br(x.path)},children:"Inspect URLs"})]})})]},x.path),vt=x.isSitemapsIndex&&Je?ze.map(st=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Kn,{value:st.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Qr(st)}),e.jsx("td",{className:"text-secondary",children:st.lastSubmitted?st.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:st.lastDownloaded?st.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Kr(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:zr(st)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!Is||ct,onClick:()=>{Zs([st.path])},children:"Resubmit"}),Ut?.sitemapUrl===st.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:pe,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{fr(st.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:ca.isPending,onClick:()=>{br(st.path)},children:"Inspect URLs"})]})})]},`${x.path}:${st.path}`)):[];return[tt,...vt]})})]}),e.jsx(Us,{page:_t.page,pageSize:ds,visibleRows:_t.rows.length,totalRows:_t.totalRows,onPageChange:_t.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(de,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:d,onChange:x=>j(x.target.value),onKeyDown:x=>x.key==="Enter"&&void wr()}),e.jsx(P,{type:"button",size:"sm",disabled:je||!Ut?.propertyId||!d.trim(),onClick:Me(wr),children:je?"Inspecting…":"Inspect URL"})]}),C&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:C.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:C.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Sr(C.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Ot(C.crawlTime)})]})]})]}),e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:M,onClick:()=>{Rn(!0)},children:M?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:Le,onChange:x=>Fe(x.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:M,onClick:()=>{Rn(!0)},children:"Apply filter"})]}),v.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:v.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-neutral",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Sr(x.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ot(x.inspectedAt)})]},x.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(de,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),g.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:g.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:x.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ot(x.transitionDate)})]},`${x.url}:${x.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ut&&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:()=>Jt(x=>!x),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${Dt?"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"})]})}),Dt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(de,{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(Xe,{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:E,disabled:Ze||m.length===0,onChange:x=>A(x.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ze?"Loading properties…":"No properties available"}):m.map(x=>e.jsxs("option",{value:x.siteUrl,children:[x.siteUrl," · ",x.permissionLevel]},x.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ze,onClick:()=>{xr(Ut,!0)},children:Ze?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!E||He,onClick:Me(Ko),children:He?"Saving…":"Save property"})]})]})]}),e.jsxs(de,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:S,onChange:x=>q(x.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:_,onChange:x=>N(x.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:la.isPending||!Ut.propertyId,onClick:Me(zo),children:la.isPending?"Queueing…":"Queue sync"}),!Ut.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const wm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Sm({projectName:t,projectId:s}){const n=Rs(),[a,r]=l.useState(null),[o,i]=l.useState(null),[m,c]=l.useState(!1),h=Ie(er({client:V,path:{name:t}})),p=h.data?.find(B=>B.connectionType==="gbp"),u=!!p,y=a?{locationName:a}:void 0,v=Ie({...kl({client:V,path:{name:t}}),enabled:u}),b=Ie({...Al({client:V,path:{name:t},query:y}),enabled:u}),g=Ie({...Pl({client:V,path:{name:t},query:y}),enabled:u}),f=Ie({...Rl({client:V,path:{name:t},query:y}),enabled:u}),C=Ie({...Il({client:V,path:{name:t},query:y}),enabled:u}),O=Ie({...Tl({client:V,path:{name:t},query:y}),enabled:u}),E=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>$l(t),enabled:u});function A(){ft(n,"gbp")}const d=qt({...Ml(),onSuccess:B=>{Ui({id:B.runId,projectId:s,kind:Ks["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),j=l.useSyncExternalStore(Bi,Qn,Qn),S=Object.values(j.runs).some(B=>B.kind===Ks["gbp-sync"]&&B.projectId===s),q=d.isPending||S,_=qt({...Ll(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!v.data)return;const B=v.data.locations.filter(ae=>ae.selected);(B.length<=1||!B.some(ae=>ae.locationName===a))&&r(null)},[a,v.data]),l.useEffect(()=>{if(!o||!v.data)return;(a?[a]:v.data.locations.filter(ae=>ae.selected).map(ae=>ae.locationName)).includes(o)||i(null)},[o,v.data,a]),h.isLoading)return null;if(!p){const B=[{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(de,{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:B.map((ae,Ne)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:Ne+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ae.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ae.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ae.note})]})]},ae.title))})]})})}const N=b.data,T=v.data?.locations??[],F=T.filter(B=>B.selected),$=g.data?.keywords??[],H=f.data?.lodging??[],ve=C.data?.placeActions??[],ue=O.data?.places??[],z=T.length>0?T[0].accountName:p.domain,ee=a?T.find(B=>B.locationName===a)?.displayName??null:null,re=a?T.filter(B=>B.locationName===a):F,W=new Set(re.map(B=>B.locationName)),K=H.filter(B=>W.has(B.locationName)),R=ve.filter(B=>W.has(B.locationName)),se=ue.filter(B=>W.has(B.locationName)),ce=new Set(F.map(B=>B.locationName)),me=a?$:$.filter(B=>ce.has(B.locationName)),X=!a&&F.length>1,Ae=(E.data??[]).filter(B=>!B.dismissed&&wm.has(B.type)&&(!ee||B.query===ee||B.query===a||B.title.startsWith(ee)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(de,{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(Xe,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:q,onClick:()=>d.mutate({client:V,path:{name:t},body:{}}),children:q?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[z?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:z})," · "]}):null,v.data?`${v.data.totalSelected} of ${v.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:B=>r(B.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),F.map(B=>e.jsx("option",{value:B.locationName,children:B.displayName},B.id))]})]}),F.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[Ae.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ae.map(B=>e.jsx("div",{className:["insight-card",qm(B.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:[B.title,B.recommendation?.reason&&e.jsx(Xe,{text:B.recommendation.reason})]})},B.id))]}),N&&e.jsx(_m,{performance:N.performance,freshness:N.freshness,timeseries:N.timeseries}),N?.profileCompleteness&&e.jsx(Cm,{summary:N.profileCompleteness}),re.length>0&&e.jsx(km,{locations:re,lodging:K,places:se,placeActions:R,expandedLocation:o,onToggleExpanded:B=>{i(ae=>ae===B?null:B)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),me.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),X&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:me.slice(0,25).map(B=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:B.keyword}),X&&e.jsx("td",{className:"text-muted",children:T.find(ae=>ae.locationName===B.locationName)?.displayName??B.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:B.valueCount!==null?B.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",B.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[B.periodStart,"–",B.periodEnd]})]},`${B.locationName}:${B.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>c(B=>!B),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",T.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:T.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!J()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:T.map(B=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:B.displayName}),e.jsx("td",{className:"text-muted",children:B.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:B.selected?"positive":"neutral",children:B.selected?"Tracked":"Not tracked"})}),!J()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:_.isPending,onClick:()=>_.mutate({client:V,path:{name:t,locationName:B.locationName},body:{selected:!B.selected}}),children:B.selected?"Untrack":"Track"})})]},B.id))})]})})]})]})})}function Cm({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:gn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:gn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:gn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:gn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:gn(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(Xe,{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 ${Em(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function km({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(h=>[h.locationName,h])),m=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const p=c.get(h.locationName)??[];p.push(h),c.set(h.locationName,p)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Xe,{text:J()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const p=i.get(h.locationName)??null,u=m.get(h.locationName)??null,y=c.get(h.locationName)??[],v=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(oe,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(oe,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:po(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Pm,{location:h})}),e.jsx("td",{children:e.jsx(Rm,{lodging:p})}),e.jsx("td",{children:e.jsx(Tm,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Mm,{actions:y})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>o(h.locationName),children:v?"Hide":"Details"})})]}),v&&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(Dm,{location:h,lodging:p,place:u,placeActions:y})})})]},h.id)})})]})})]})}function Am(t){return[{label:"Description",tone:qs(t.description)?"positive":"neutral",value:qs(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:qs(t.primaryPhone)?"positive":"neutral",value:qs(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:qs(t.websiteUri)?"positive":"neutral",value:qs(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function Pm({location:t}){const s=Am(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Rm({lodging:t}){return e.jsx(sr,{...Im(t)})}function Im(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 Tm({place:t,mapsUri:s}){return e.jsx(sr,{...$m(t,s)})}function $m(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 Mm({actions:t}){return e.jsx(sr,{...Lm(t)})}function Lm(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 sr({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Dm({location:t,lodging:s,place:n,placeActions:a}){const r=s?Gm(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(wa,{title:"Owner profile · Business Information",children:[e.jsx(Rt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Rt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Rt,{label:"Description",value:qs(t.description)?t.description:"Not returned"}),e.jsx(Rt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Rt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Rt,{label:"Open status",value:po(t.openStatus)}),e.jsx(Rt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(wa,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Last checked",value:Hr(s.syncedAt)}),e.jsx(Rt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Rt,{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(wa,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Places tier",value:n.tier}),e.jsx(Rt,{label:"Last checked",value:Hr(n.syncedAt)}),e.jsx(Rt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[ta(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[ta(o.providerType),o.uri?` · ${Om(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function wa({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Rt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function gn(t,s,n){return t===s?"positive":t===0?n:"caution"}function Em(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function qm(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function qs(t){return typeof t=="string"&&t.trim().length>0}function po(t){return t?ta(t):"Not returned"}function ta(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Om(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 Gm(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Fm(n)).map(([s])=>ta(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Fm(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function _m({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Dl.filter(b=>(a[b]??0)>0),o=El.filter(b=>(a[b]??0)>0),i=Object.keys(a).filter(b=>(a[b]??0)>0&&ql(b)==="other").sort((b,g)=>(a[g]??0)-(a[b]??0)),m=Object.keys(a).filter(b=>(a[b]??0)===0).sort(),c=n.map(b=>{const g={date:b.date};for(const[f,C]of Object.entries(b.metrics))g[f]=C;return g}),h=n.find(b=>b.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,u=c.length>0,y=s.dataThroughDate?`Data through ${$t(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,v=[...r,...i];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),y&&e.jsx("span",{className:"text-[11px] text-muted",children:y})]}),!u||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{data:c,metrics:r,kind:"line",firstPending:h,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:v.map(b=>e.jsxs("span",{className:"text-sm text-secondary",children:[Hn(b)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[b]??0).toLocaleString()})]},b))})]})]}),u&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Wr,{data:c,metrics:o,kind:"area",firstPending:h,lastDate:p})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(b=>Hn(b)).join(", ")]})]})}function Wr({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Qs,{width:"100%",height:"100%",children:e.jsxs(Hs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Zn,{stroke:Jn,vertical:!1}),e.jsx(Ws,{dataKey:"date",tick:Gt,tickLine:!1,axisLine:{stroke:ss},tickFormatter:zs,minTickGap:24}),e.jsx(Ys,{tick:Gt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Xs,{...Wt,labelFormatter:$t,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),Hn(String(i??""))]}),e.jsx(ea,{wrapperStyle:{fontSize:11,color:Xt.text},formatter:o=>Hn(o)}),a&&r&&e.jsx(Ba,{x1:a,x2:r,fill:Xt.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Xt.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Gs,{type:"monotone",dataKey:o,stroke:nt[i%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Cs,{type:"monotone",dataKey:o,stackId:"reach",stroke:nt[i%nt.length],fill:nt[i%nt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Um(t){return eo(xs(String(t)))}function Bm(t){return Ps(xs(String(t)))}function Sa({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[o,i]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":o?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(ru,{className:"h-3.5 w-3.5","aria-hidden":!0})}),o&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Dn=ds;function en(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Ca(t){return t.toLocaleString()}function Vm(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Km(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 zm(t){const s=t.filter(n=>n.kind===Ks["backlink-extract"]&&!Vi(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Qm(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),o=a%60;return o===0?`${r}m`:`${r}m ${o}s`}function Hm({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[m,c]=l.useState(null),[h,p]=l.useState(null),[u,y]=l.useState(null),[v,b]=l.useState(Date.now()),[g,f]=l.useState(0),[C,O]=l.useState(!0),[E,A]=l.useState(!1),[d,j]=l.useState(null),S=l.useCallback(async()=>{O(!0),j(null);try{const[z,ee,re,W,K]=await Promise.all([Ol().catch(()=>null),Gl(t,{excludeCrawlers:!0}).catch(()=>null),Fl(t,{limit:Dn,offset:g,excludeCrawlers:!0}).catch(se=>{if(se instanceof dn&&se.code==="NOT_FOUND")return null;throw se}),_l(t).catch(()=>[]),Ul(t).catch(()=>[])]);c(z),n(ee),r(re),i(W);const R=zm(K);p(R)}catch(z){j(z instanceof Error?z.message:"Failed to load backlinks")}finally{O(!1)}},[t,g]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!h)return;const z=h.id;let ee=!1;const re=async()=>{try{const K=await Ua(z);if(ee)return;Vi(K.status)?(p(null),y(K),await S()):p(R=>R?.id===K.id?{...R,...K}:R)}catch{}},W=window.setInterval(()=>{re()},3e3);return()=>{ee=!0,window.clearInterval(W)}},[h,S]),l.useEffect(()=>{if(!h)return;const z=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(z)},[h]),l.useEffect(()=>{if(!u||u.status==="failed")return;const z=window.setTimeout(()=>y(null),1e4);return()=>window.clearTimeout(z)},[u]);async function q(){A(!0),j(null);try{const z=await Vl(t);p(z)}catch(z){z instanceof dn&&z.code==="MISSING_DEPENDENCY"?j("DuckDB is not installed. Visit the Backlinks admin page to install it."):j(z instanceof Error?z.message:"Failed to trigger extract")}finally{A(!1)}}const _=l.useMemo(()=>o.slice().sort((z,ee)=>z.queriedAt.localeCompare(ee.queriedAt)).map(z=>({date:z.queriedAt,linkingDomains:z.totalLinkingDomains})),[o]),N=a?.rows??[],T=a?.total??0,F=s?.excludedLinkingDomains??0,$=Math.floor(g/Dn)+1;return l.useEffect(()=>{g>0&&g>=T&&f(0)},[g,T]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),d&&e.jsx(de,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:d})}),h&&e.jsx(de,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(nu,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(oe,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Qm(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",v]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),u&&!h&&e.jsx(de,{className:`surface-card p-4 mb-4 ${u.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[u.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Xi,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${u.status==="failed"?"text-negative":"text-positive"}`,children:u.status==="failed"?"Extract failed":"Extract complete"}),u.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Bl(u.error)}):u.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return C?e.jsx(de,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):ve()}function ve(){const z=s!==null&&s.totalLinkingDomains>0,ee=u?.status==="failed",re=s!==null&&s.totalLinkingDomains===0&&!ee,W=m?.status==="ready",K=m?.status==="failed",R=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return z?ue(e.jsxs(e.Fragment,{children:[!J()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:E||h!==null,onClick:Me(q),children:[e.jsx(Ji,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":E?"Queuing…":"Re-run extract"]}),e.jsx(Sa,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!J()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:en("/backlinks"),children:"Open admin"})})]})):e.jsx(de,{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(au,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:en("/backlinks"),children:"Set up backlinks"})})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:en("/backlinks"),children:"View sync status"})})})]}),K&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:en("/backlinks"),children:"Go to Backlinks admin"})})})]}),W&&!R&&!re&&!ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:m.release})," is ready. Run an extract for this project."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:E||h!==null,onClick:Me(q),children:[e.jsx(Yn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":E?"Queuing…":"Run extract"]}),e.jsx(Sa,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!J()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:en("/backlinks"),children:"Go to Backlinks admin"})})})]}),re&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:en("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:E||h!==null,onClick:Me(q),children:[e.jsx(Yn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":E?"Queuing…":"Re-run extract"]}),e.jsxs(Sa,{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 ue(z){if(!s)return null;const ee="Linking hosts",re="linking hosts",W="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ca(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",re]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ca(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",re," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Vm(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",re," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",W," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Km(s.queriedAt),F>0&&e.jsxs(e.Fragment,{children:[" · ",F," excluded domain",F===1?"":"s"]})]}),_.length>=2&&e.jsxs(de,{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(Qs,{width:"100%",height:"100%",children:e.jsxs(Hs,{data:_,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:nt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:nt[0],stopOpacity:0})]})}),e.jsx(Ws,{dataKey:"date",tick:Gt,stroke:ss,tickFormatter:Um}),e.jsx(Ys,{tick:Gt,stroke:ss,allowDecimals:!1}),e.jsx(Xs,{contentStyle:Wt.contentStyle,labelStyle:Wt.labelStyle,itemStyle:Wt.itemStyle,labelFormatter:Bm}),e.jsx(Cs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:nt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(de,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:ee})]})}),e.jsxs("tbody",{children:[N.map(K=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:K.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Ca(K.numHosts)})]},K.linkingDomain)),N.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:F>0&&T===0?`Every referring domain in this ${W} was a crawler/proxy host (${F} hidden).`:`No referring domains in this ${W}.`})})]})]})}),e.jsx(Us,{page:$,pageSize:Dn,visibleRows:N.length,totalRows:T,onPageChange:K=>f((K-1)*Dn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:z})]})}}function Wm({projectName:t}){const s=Ie({...Kl({client:V,path:{name:t}}),staleTime:Ki}),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:tr(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:o,providersConfigured:i}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",i," engines",e.jsx(Xe,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",o," of ",i," engine answers",e.jsx(Xe,{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(Ym,{data:n}),e.jsx(Xm,{data:n}),n.competitorGaps.length>0&&e.jsx(th,{data:n})]})}function Ym({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:o}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(En,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(En,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(En,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(En,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function En({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 Xm({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(Jm,{}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(cn,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(o=>o.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(iu,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Zm,{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 Jm(){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(an,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(an,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(an,{active:!1,tone:"cited"}),e.jsx(an,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Zm({provider:t}){const s=eh(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(an,{active:t.cited,tone:"cited"}),e.jsx(an,{active:t.mentioned,tone:"mentioned"})]})}function eh(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 an({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 th({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(Xe,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(cn,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const An="__cited__",Pn="__mentioned__",Yt="__mentionShare__";function go(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:xs(n),end:xs(a),sweepCount:s.sweepCount??1}}function sa(t){const s=go(t);if(!s)return"Sweep date unavailable";const n=Ps(s.start),a=Ps(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function sh(t){const s=go(t);return s?eo(s.start):""}function mn(t){return t.trim().toLowerCase()}function Qa(t){return Math.round(t*1e3)/10}function Ha(t){return t.byProvider??{}}function nh(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?An:Pn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[c]:Qa(u[h])})),series:[c],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(c=>Object.keys(Ha(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},p=Ha(c);for(const u of i){const y=p[u];h[u]=y?Qa(y[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function fo(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function ah(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function rh(t){return t.servedModelAttribution??{}}function ih(t){return t.modelServiceMismatch??{}}function oh(t){return t.modelPointerChanges??{}}function lh(t){return t.length>0?t.join(", "):null}function Yr(t,s){const n=mn(s);return Object.entries(t).find(([a])=>mn(a)===n)?.[1]}function us(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 ch(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Yr(Ha(a),s))continue;const r=fo(a);return r?Yr(r,s)??null:null}return null}function dh(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const o=s.get(r.bucketStartDate)??[];o.push({provider:n,event:r}),s.set(r.bucketStartDate,o)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,o)=>r.provider.localeCompare(o.provider)||r.event.observedAt.localeCompare(o.event.observedAt))}))}function uh(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const o=r.events.filter(i=>!i.fromPreWindowAnchor);for(const i of r.events)i.fromPreWindowAnchor&&n.push({provider:a,event:i});o.length>0&&(s[a]={...r,events:o})}return{buckets:dh(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function mh(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 hh(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 xh(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[Yt]:r?.rate==null?null:Qa(r.rate)}}),n=s.map(a=>a[Yt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Yt],hasData:n.length>0,singleBucket:n.length===1}}function ph(t,s,n){return s==="mentionShare"?xh(t):nh(t,s,n)}function Xr(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 Jr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Zr(t){return t>0?`+${t}`:`${t}`}function gh(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Zr(n.delta)} on ${Jr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Zr(s.delta)} on ${Jr(s.date)})`}const fh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],bh=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],yh=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"On non-brand queries, the share of answer-text brand mentions for you and tracked competitors that were you. Pooled only when query classification is unavailable."}],nr=nt[2],vh="var(--chart-tooltip-bg)",jh={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function hs(t){const s=mn(t);return jh[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ks(t){return Math.round(t*10)/10}function Nh(t){return t===An||t===Pn||t===Yt}function bo(t){return t===An?"Cited":t===Pn?"Mentioned":t===Yt?"Mention share":hs(t)}function yn(t,s){return t===An?Bs.positive:t===Pn?nt[1]:t===Yt?nr:cu(mn(t),s)}function wh(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Sh(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
+
`)}function ia(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function zn(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${ia(s)}`:"Mention share":"Mentioned"}function Cn(t){return t==="cited"?"citationRate":"mentionRate"}function yo(t,s){return s==="cited"?t.cited:t.mentionedCount}function vo(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 jo(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Wa(t){const s=fo(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>mn(a).localeCompare(mn(r))).map(([a,r])=>`${hs(a)}: ${us(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Ch(t){return t.some(({event:s})=>s.to.status==="mixed")?Bs.caution:t.some(({event:s})=>s.to.status==="unknown")?Bs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:Bs.positive}function kh(t,s,n){const a=jo(t,s);return a?sa(a):Ps(xs(n))}function Ah({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:m}){const c=l.useId(),h=Object.entries(o).sort(([u],[y])=>u.localeCompare(y)),p=t.buckets.length>0||t.beforeWindow.length>0;return!s||!p?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":c,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:c,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:u,events:y})=>y.map(({provider:v,event:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:kh(m,u,b.observedAt)}),e.jsxs("span",{children:[hs(v),": ",us(b.from)," → ",us(b.to)]})]},`${v}-${b.observedAt}-${b.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:u,event:y})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Ps(xs(y.observedAt))]}),e.jsxs("span",{children:[hs(u),": ",us(y.from)," → ",us(y.to),y.anchorObservedAt?` (last seen ${us(y.from)} on ${Ps(xs(y.anchorObservedAt))})`:""]})]},`before-${u}-${y.observedAt}`))})]}),a.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:[hs(u.provider),": showing the most recent ",u.shown," of ",u.total," changes."]},`truncated-${u.provider}`)),r.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",hs(u)," change."]},`incomplete-${u}`)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([u,y])=>{const v=lh(y.latestServedModelIds),b=i[u];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Ps(xs(y.latestObservation.observedAt))}),e.jsxs("span",{children:[hs(u),": ",v??us(y.latestObservation.state),b?` — not the ${us(b.configured)} you selected`:""]})]},`served-${u}`)})})]})]})}function ei(t){return t===null?"no data":`${t}%`}function ka(t){return t==null?"undefined":`${ks(t*100)}%`}function Ph({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=jo(o,s);if(!i)return null;if(a==="mentionShare"){const c=i.mentionShare.projectMentionSnapshots,h=i.mentionShare.competitorMentionSnapshots,p=c+h,u=i.mentionShare.rate==null?null:ks(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:sa(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:nr},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",ia(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:ei(u)})]}),p>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",p," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:Wa(i)})]})}const m=r==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?An:Pn,value:ks(i[Cn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:sa(i)}),m.map((c,h)=>{const p=String(c.dataKey??c.name??""),u=r==="byProvider"?vo(i,p,a):null,y=u?.count??yo(i,a),v=u?.total??i.total,b=typeof c.value=="number"?c.value:ks(u?u.rate*100:i[Cn(a)]*100),g=c.color??yn(p,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:g},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:bo(p)}),e.jsx("span",{className:"trend-tooltip-value",children:ei(b)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[y," / ",v," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${p}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Wa(i)})]})}function Rh({buckets:t,metric:s,mode:n,series:a}){const r=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[zn(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(o=>{let i;if(s==="mentionShare"){const m=o.mentionShare.projectMentionSnapshots,c=o.mentionShare.competitorMentionSnapshots,h=m+c,p=ia(o.mentionShare.scope);i=h>0?`${ka(o.mentionShare.rate)} mention share for ${p}, ${m} of ${h} brand mentions were you`:`mention share undefined for ${p}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(m=>{const c=vo(o,m,s);return c?`${hs(m)} ${ka(c.rate)} ${zn(s).toLowerCase()}, ${c.count} of ${c.total} snapshots`:`${hs(m)} no data`}).join("; "):i=`${ka(o[Cn(s)])} ${zn(s).toLowerCase()}, ${yo(o,s)} of ${o.total} snapshots`;return i+=`; ${Wa(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:sa(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function Aa({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const o=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(i=>{const m=s===i.value,c=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":m,"aria-describedby":c,className:`segmented-option ${m?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:c,className:"sr-only",children:i.description})]},i.value)})})}function Ih({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[m,c]=l.useState("byProvider"),h=l.useMemo(()=>Sh(s),[s]),p=Ie({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>zl(t,a),staleTime:Ki}),u=p.data??null,y=p.error,v=o==="mentionShare"?"overall":m,b=l.useMemo(()=>u?ph(u,o,v):null,[u,o,v]),g=u?ah(u):null,f=l.useMemo(()=>uh(g??{}),[g]),C=l.useMemo(()=>mh(g??{}),[g]),O=l.useMemo(()=>hh(g??{}),[g]),E=l.useMemo(()=>Object.entries(g??{}).filter(([,K])=>K.anchorUnavailable).map(([K])=>K).sort(),[g]),A=l.useMemo(()=>u?rh(u):{},[u]),d=l.useMemo(()=>u?ih(u):{},[u]),j=l.useMemo(()=>u?Ql(oh(u)):null,[u]),S=o!=="mentionShare"&&v==="byProvider",q=u?.buckets??[],_=q[q.length-1]?.mentionShare.scope??u?.mentionShareScope??"pooled",N=zn(o,_),T=o==="cited"?Bs.positive:o==="mentionShare"?nr:nt[1],F=S?Xt.textDim:T,$=l.useMemo(()=>{const K=new Map(q.map(R=>[R.startDate,sh(R)]));return R=>K.get(String(R))??""},[q]),H=o==="mentionShare"?b?Xr(b.rows,Yt):null:q.length>0?ks(q[q.length-1][Cn(o)]*100):null,ve=o==="mentionShare"?b?wh(b.rows,Yt):null:q.length>0?ks(q[0][Cn(o)]*100):null,ue=o==="mentionShare"?b?.rows.filter(K=>typeof K[Yt]=="number").length??0:q.length,z=H!==null&&ve!==null&&ue>1?ks(H-ve):null,ee=s.length,re=e.jsxs(e.Fragment,{children:[j?.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:j.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(Xe,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use all query-provider snapshots. Mention share uses non-brand queries when classification is available; pooled means the project has no usable brand identity for a split."})]})]}),H!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:F},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:N}),S&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[H,"%"]}),z!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${z>0?"text-positive-400":z<0?"text-negative-400":"text-muted"}`,children:[z>0?"+":"",z.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Aa,{options:yh,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(Aa,{options:bh,value:m,onChange:c,ariaLabel:"Series"}),e.jsx(Aa,{options:fh,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let W;if(y)W=e.jsx("p",{className:"text-sm text-negative-400",children:tr(y)});else if(p.isLoading&&!u)W=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&ee===0)W=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!u||!b)W=null;else{const{rows:K,series:R,hasData:se}=b,ce=gh(u.queryChanges);if(!se)W=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${ia(_)} in this window yet.`:"Run a sweep to start tracking citations and mentions over time."});else if(S&&R.length===0)W=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const me=`${N} rate across ${K.length} ${K.length===1?"sweep":"sweeps"}. Latest ${H}%${z!==null?`, ${z>=0?"up":"down"} ${Math.abs(z).toFixed(1)} points over the period`:""}.`;W=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:me}),e.jsx(Rh,{buckets:q,metric:o,mode:v,series:R}),S&&R.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:R.map((X,Ae)=>{const B=Xr(K,X),ae=ch(q,X),Ne=g===null?"Attribution unavailable":ae?us(ae):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:yn(X,Ae)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:bo(X)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),Ne]})]}),B!==null&&e.jsxs("span",{className:"trend-legend-value",children:[B,"%"]})]},X)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${N} trend chart over ${K.length} ${K.length===1?"bucket":"buckets"}`,children:e.jsx(Qs,{width:"100%",height:"100%",children:e.jsxs(Hs,{data:K,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Zn,{stroke:Jn,vertical:!1}),e.jsx(Ws,{dataKey:"date",tick:Gt,tickLine:!1,axisLine:{stroke:ss},tickFormatter:$,minTickGap:24}),e.jsx(Ys,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:X=>`${X}%`,tick:Gt,tickLine:!1,axisLine:!1,width:40}),e.jsx(Xs,{cursor:{stroke:ss,strokeWidth:1},content:e.jsx(Ph,{metric:o,mode:v,buckets:q})}),f.buckets.map(({bucketStartDate:X,events:Ae})=>e.jsx(pu,{x:X,stroke:Ch(Ae),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${X}`)),R.map((X,Ae)=>e.jsx(Gs,{type:"monotone",dataKey:X,name:X,stroke:yn(X,Ae),strokeDasharray:X===Yt?"5 4":void 0,strokeWidth:Nh(X)?2.5:2,dot:X===Yt?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:yn(X,Ae),strokeWidth:1.5}:{r:2.5,fill:yn(X,Ae),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:vh},connectNulls:X!==Yt,isAnimationActive:!1},X))]})})}),e.jsx(Ah,{partition:f,available:g!==null,counts:C,truncated:O,incompleteHistory:E,served:A,mismatch:d,buckets:q}),ce&&e.jsx("p",{className:"visibility-trend-note",children:ce})]})}}return e.jsxs("section",{className:"visibility-trend",children:[re,W]})}const ti=new Set([Nn.queued,Nn.running]);function Th({projectName:t}){const s=Rs(),[n,a]=l.useState(""),[r,o]=l.useState(""),[i,m]=l.useState(""),[c,h]=l.useState("__default__"),[p,u]=l.useState(null),y=Ie({...Hl({client:V,path:{name:t}}),staleTime:6e4}),v=Ie({...Wl({client:V}),staleTime:6e4}),b=Ie({...Yl({client:V,path:{name:t},query:{limit:20}}),refetchInterval:N=>N.state.data?.runs.some(T=>ti.has(T.status))?3e3:!1}),g=b.data?.runs??[];l.useEffect(()=>{!p&&g[0]&&u(g[0].id)},[g,p]);const f=g.find(N=>N.id===p)??null,C=Ie({...Xl({client:V,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:f&&ti.has(f.status)?3e3:!1}),O=C.data??null,E=l.useMemo(()=>Lh(n),[n]),A=y.data?.locations??[],d=l.useMemo(()=>{const N=new Map((v.data?.providerCatalog??[]).map(T=>[T.name,T]));return(v.data?.providers??[]).filter(T=>T.configured&&N.get(T.name)?.mode==="api").map(T=>({...T,catalog:N.get(T.name)}))},[v.data]),j=!v.isLoading&&d.length===0,S=d.find(N=>N.name===r)??null;l.useEffect(()=>{r&&!S&&(o(""),m(""))},[r,S]);const q=qt({...Jl(),onSuccess:async N=>{u(N.id),a(""),m(""),await Oh(s),Se({title:"Research batch saved",detail:`${N.totalQueries} quer${N.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${N.id}`,dedupeMode:"replace"})},onError:N=>{Se({title:"Could not start research",detail:N instanceof Error?N.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function _(){if(E.length===0||E.length>50||j||q.isPending||J())return;const N=c==="__default__"?void 0:c==="__none__"?null:A.find(T=>T.label===c)??void 0;q.mutate({client:V,path:{name:t},body:{queries:E,...r?{provider:r}:{},...r&&i.trim()?{model:i.trim()}:{},...N!==void 0?{location:N}:{}}})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(de,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific queries against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:`one query per line
|
|
3
|
+
e.g. What is the best way to choose an AEO platform?`,value:n,onChange:N=>a(N.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${E.length>50?"text-negative":"text-faint"}`,children:[E.length," ",E.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:r,onChange:N=>{o(N.target.value),m("")},children:[e.jsx("option",{value:"",children:"Project default"}),d.map(N=>e.jsx("option",{value:N.name,children:N.displayName??N.name},N.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:c,onChange:N=>h(N.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),A.map(N=>e.jsx("option",{value:N.label,children:N.label},N.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:S?`Default: ${S.model??S.defaultModel??S.catalog.defaultModel}`:"Choose a provider to select an exact model",value:i,disabled:!S,onChange:N=>m(N.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(S?.catalog.knownModels??[]).map(N=>e.jsx("option",{value:N.id,children:N.displayName},N.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:E.length===0||E.length>50||j||q.isPending,onClick:_,children:[e.jsx(Yn,{size:14}),q.isPending?"Starting research…":`Run ${E.length||""} research ${E.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."})]}),j&&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(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Saved research batches"})]}),b.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),g.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more queries to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:g.map(N=>e.jsxs("tr",{className:p===N.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>u(N.id),children:Dh(N.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:N.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:N.requestedModel??N.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:N.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[N.completedQueries+N.failedQueries,"/",N.totalQueries]}),e.jsx("td",{children:e.jsx(oe,{tone:No(N.status),children:N.status})})]},N.id))})]})})]})]}),e.jsx($h,{detail:O,isLoading:C.isFetching})]})}function $h({detail:t,isLoading:s}){const[n,a]=l.useState(null);l.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const r=t?.queries.find(o=>o.id===n)??t?.queries[0]??null;return e.jsxs(de,{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 ${Eh(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(oe,{tone:No(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(o=>e.jsxs("tr",{className:r?.id===o.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(o.id),children:o.query})}),e.jsx("td",{children:e.jsx(oe,{tone:qh(o.status),children:o.status})}),e.jsx("td",{children:e.jsx(oe,{tone:o.answerMentioned===!0?"positive":o.answerMentioned===!1?"neutral":o.status===_s.failed?"negative":"caution",children:o.answerMentioned===null?o.status===_s.failed?"Unavailable":"Pending":o.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(oe,{tone:o.citationState==="cited"?"positive":o.citationState==="not-cited"?"neutral":o.status===_s.failed?"negative":"caution",children:o.citationState===null?o.status===_s.failed?"Unavailable":"Pending":o.citationState==="cited"?"Cited":"Not cited"})})]},o.id))})]})}),e.jsx(Mh,{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 Mh({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===_s.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=Es(n.uri),o=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[r?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:o}):e.jsx("span",{className:"truncate text-secondary",children:o}),r&&e.jsx(ou,{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 Lh(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 Dh(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 Eh(t){return t.length>8?t.slice(0,8):t}function No(t){return t===Nn.completed?"positive":t===Nn.partial?"caution":t===Nn.failed?"negative":"neutral"}function qh(t){return t===_s.completed?"positive":t===_s.failed?"negative":"neutral"}async function Oh(t){await ft(t,"researchRuns")}const Ya=new Set(["queued","seeding","probing"]);function Gh({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(Fh,{projectName:t}):e.jsx(Th,{projectName:t})})]})}function Fh({projectName:t}){const s=Rs(),[n,a]=l.useState(null),[r,o]=l.useState(""),[i,m]=l.useState("100"),c=Ie({...Zl({client:V,path:{name:t},query:{limit:"10"}}),refetchInterval:d=>d.state.data?.some(S=>Ya.has(S.status))?3e3:!1}),h=c.data??[];l.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const p=h.find(d=>d.id===n)??null,u=Ie({...ec({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&Ya.has(p.status)?3e3:!1}),y=u.data??null,v=Ie({...tc({client:V,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),b=qt({mutationFn:()=>{const d={},j=r.trim();j&&(d.icpDescription=j);const S=Number.parseInt(i,10);return Number.isFinite(S)&&S>0&&(d.maxProbes=S),sc(t,d)},onSuccess:async d=>{a(d.sessionId),o(""),await ni(s,t,d.sessionId),Se({title:"Discovery started",detail:`Run ${Pa(d.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${d.sessionId}`,dedupeMode:"replace"})},onError:d=>{Se({title:"Discovery failed to start",detail:d instanceof Error?d.message:"Could not start discovery.",tone:"negative"})}}),g=qt({mutationFn:d=>{if(!n)throw new Error("Select a completed discovery session first.");return nc(t,n,d)},onSuccess:async d=>{await ni(s,t,d.sessionId),s.invalidateQueries({queryKey:zi({client:V})}),s.invalidateQueries({predicate:j=>Array.isArray(j.queryKey)&&j.queryKey[0]==="projects"&&j.queryKey.length>1}),Se({title:"Queries added",detail:Vh(d),tone:"positive",dedupeKey:`discovery:promote:${d.sessionId}`,dedupeMode:"replace"})},onError:d=>{Se({title:"Could not add queries",detail:d instanceof Error?d.message:"Could not add queries from this run.",tone:"negative"})}}),f=y??p,C=v.data??null,O=(C?.queriesByBucket.cited.length??0)+(C?.queriesByBucket.aspirational.length??0),E=l.useMemo(()=>(y?.probes??[]).slice(0,30),[y?.probes]);async function A(){try{const d=await c.refetch();if(d.error)throw d.error;const j=d.data?.length??0;Se({title:"Discovery sessions refreshed",detail:`${j} recent session${j===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(d){Se({title:"Discovery refresh failed",detail:d instanceof Error?d.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:J()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:c.isFetching,onClick:()=>{A()},children:[e.jsx(Wn,{className:`size-3.5 ${c.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(oe,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:r,onChange:d=>o(d.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:i,onChange:d=>m(d.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:b.isPending,onClick:()=>b.mutate(),children:[e.jsx(Yn,{size:14}),b.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),c.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),h.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:h.map(d=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===d.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(d.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:Pa(d.id)}),e.jsx(oe,{tone:si(d.status),children:d.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",d.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",d.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",d.wastedCount??0]})]})]},d.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:f?Pa(f.id):"No run selected"})]}),f&&e.jsx(oe,{tone:si(f.status),children:f.status})]}),f?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ns,{label:"Questions tested",value:f.probeCount??0}),e.jsx(Ns,{label:"Cited queries",value:f.citedCount??0,tone:"positive"}),e.jsx(Ns,{label:"Worth tracking",value:f.aspirationalCount??0,tone:"caution"}),e.jsx(Ns,{label:"Skip",value:f.wastedCount??0,tone:"negative"})]}),f.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:f.error}),f.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:f.warning}),f.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:f.icpDescription})]}),f.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:f.competitorMap.slice(0,8).map(d=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[d.domain," ",e.jsx("span",{className:"text-muted",children:d.hits})]},d.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),f?.status==="completed"&&e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Choose queries to track"})]}),!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:g.isPending||O===0,onClick:()=>g.mutate(void 0),children:[e.jsx(Xi,{size:14}),g.isPending?"Adding…":"Add recommended queries"]})]}),v.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):C?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ns,{label:"Queries to add",value:O,tone:"positive"}),e.jsx(Ns,{label:"Cited queries",value:C.queriesByBucket.cited.length,tone:"positive"}),e.jsx(Ns,{label:"Worth tracking",value:C.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(Ns,{label:"Skip",value:C.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Adds Cited queries and Worth tracking queries, plus recurring competitor sites. Skip items remain available for review only."}),C.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.suggestedCompetitors.map(d=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[d.domain," ",e.jsx("span",{className:"text-muted",children:d.hits})]},d.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),u.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),E.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:E.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:d.query}),e.jsx("td",{children:e.jsx(oe,{tone:_h(d.bucket),children:Bh(d.bucket)})}),e.jsx("td",{className:"text-secondary",children:d.citedDomains.length>0?d.citedDomains.slice(0,3).join(", "):"-"})]},d.id))})]})})]})]})]})]})}function Ns({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 si(t){return t==="completed"?"positive":t==="failed"?"negative":Ya.has(t)?"caution":"neutral"}function _h(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Uh={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Bh(t){return t?Uh[t]:"Not classified"}function Pa(t){return t.length>8?t.slice(0,8):t}function Vh(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 ni(t,s,n){await Promise.all([ft(t,"discovery"),t.invalidateQueries({queryKey:ac({client:V})})])}function ai(t){return`${(t*100).toFixed(1)}%`}function Kh({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),m=Ie({...rc({client:V,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=Ie({...ic({client:V,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(c.data??[]).filter(f=>(f.status==="completed"||f.status==="partial")&&f.trigger!=="probe").reverse(),p=o??h[0]?.id??"",u=a??h.find(f=>f.id!==p)?.id??"",y=!!(u&&p&&u!==p),v=Ie({...oc({client:V,path:{name:t},query:{run1:u,run2:p}}),enabled:s==="compare"&&y}),b=m.data??[],g=v.data?.diff.filter(f=>f.changed||f.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([f,C])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===f,className:`filter-chip ${s===f?"filter-chip-active":""}`,onClick:()=>n(f),children:C},f))}),s==="changes"?e.jsx(gu,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),m.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!m.isLoading&&b.length===0?e.jsxs(de,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,b.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:b.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(f.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.mentionedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:ai(f.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.citedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:ai(f.overallCitedRate)})]},f.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:u,onChange:f=>r(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:p,onChange:f=>i(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]})]}),c.isLoading||v.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&h.length<2?e.jsxs(de,{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,v.data&&g.length===0?e.jsxs(de,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,g.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:g.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:f.query??"Archived query"}),e.jsx("td",{children:e.jsxs(oe,{tone:f.changed?"caution":"neutral",children:[f.run1State??"none"," → ",f.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(oe,{tone:f.visibilityChanged?"caution":"neutral",children:[f.run1MentionState??"none"," → ",f.run2MentionState??"none"]})})]},f.queryId??f.query??"unknown"))})]})}):null]}):null]})}const ri={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},zh={contract:null,assessment:null,googleAds:ri,gtm:ri,snapshots:[]};function Qh(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Xh(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Hh(t){switch(t){case"configured":return{label:"Configured",detail:"The conversion is declared, but the static configuration is not yet proven consistent.",tone:"caution"};case"static-mismatch":return{label:"Static mismatch",detail:"Stored configuration does not match the declared conversion. Review the failing checks before relying on it.",tone:"negative"};case"statically-consistent":return{label:"Statically consistent",detail:"Stored Google Ads and Tag Manager configuration aligns with the declared conversion.",tone:"positive"};case"runtime-unverified":return{label:"Runtime verification needed",detail:"The stored configuration aligns, but a real browser event has not been observed.",tone:"caution"};case"observed":return{label:"Observed",detail:"Stored static evidence and a runtime observation support this conversion path.",tone:"positive"};case"not-configured":return{label:"Setup needed",detail:"Connect both providers, select their resources, then declare the conversion Canonry should inspect.",tone:"neutral"};case"contract-selection-required":return{label:"Choose conversion",detail:"Choose one of the declared conversions before Canonry evaluates its evidence.",tone:"neutral"};case"assessment-loading":return{label:"Checking configuration",detail:"Canonry is loading the selected conversion assessment.",tone:"neutral"};case"assessment-unavailable":return{label:"Assessment unavailable",detail:"The selected conversion could not be assessed. Retry before treating static evidence as current.",tone:"negative"}}}function Wh(t){switch(t.googleAds.state){case"not-connected":return{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."};case"selection-required":return{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."};case"stale":return{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."};default:return null}}function Yh(t){switch(t.gtm.state){case"not-connected":return{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."};case"selection-required":return{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."};case"stale":return{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."};default:return null}}function wo(t){return t.googleAds.state==="not-connected"?{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."}:t.googleAds.state==="unavailable"||t.gtm.state==="unavailable"?{id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."}:t.googleAds.state==="selection-required"?{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."}:t.googleAds.state==="stale"?{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."}:t.gtm.state==="not-connected"?{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."}:t.gtm.state==="selection-required"?{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."}:t.gtm.state==="stale"?{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."}:t.contractSelectionRequired?{id:"select-contract",label:"Select conversion",detail:"Choose the declared conversion Canonry should assess."}:t.contract?t.assessmentState==="loading"?{id:"waiting-for-integrity",label:"Checking configuration…",detail:"Canonry is loading the selected conversion assessment."}:t.assessmentState==="unavailable"?{id:"retry-integrity",label:"Retry assessment",detail:"Retry the selected conversion assessment before acting on its evidence."}:t.assessment?.status==="runtime-unverified"?{id:"review-runtime-verification",label:"Review runtime verification",detail:"Static configuration is aligned. Verify a real browser event separately."}:t.assessment?.status==="configured"&&Jh(t)?{id:"review-findings",label:"Review findings",detail:"Resolve the mismatched or unknown checks before treating this conversion as ready."}:{id:"sync-static-evidence",label:"Refresh static evidence",detail:"Queue fresh read-only Google Ads and Tag Manager observations."}:{id:"declare-contract",label:"Declare conversion",detail:"Name the website event, Google Ads action, and Tag Manager tag that must agree."}}function Xh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Jh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function So(t){switch(t){case"connected":return{label:"Connected",tone:"positive"};case"stale":return{label:"Needs refresh",tone:"caution"};case"selection-required":return{label:"Selection needed",tone:"caution"};case"not-connected":return{label:"Not connected",tone:"neutral"};case"unavailable":return{label:"Unavailable",tone:"negative"}}}function Zh(t,s){return t==="configured"?s==="not-configured"||s==="contract-selection-required"?"neutral":"positive":t==="static"?s==="assessment-unavailable"?"negative":s==="assessment-loading"?"neutral":s==="static-mismatch"?"negative":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"positive":s==="configured"?"caution":"neutral":s==="observed"?"positive":s==="runtime-unverified"?"caution":"neutral"}function ex(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function $s(t){return t.length<=12?t:`…${t.slice(-10)}`}function tx(t){const s=[];return t.googleAds.requirePrimaryAction&&s.push("primary action"),t.googleAds.requireBiddableGoal&&s.push("biddable goal"),s.length>0?s.join(" and "):"No bidding-goal assertion"}function sx(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"No additional event fields required"}const Ra={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function ii(t){return t.outcome==="pass"?{label:Ra[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Ra[t.code],tone:"negative",outcome:"Fail"}:{label:Ra[t.code],tone:"caution",outcome:"Unknown"}}function nx(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function ax(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("conversion value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"no additional event fields"}function rx(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function oi({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=So(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(oe,{tone:o.tone,children:o.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Ot(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const ix="A conversion names the website event, the Google Ads conversion action, and the Tag Manager tag that must agree. It needs both connections selected because it references resources from each.",ox="Available once Google Ads and Tag Manager are connected.",lx="Check that a conversion is wired the same way in Google Ads and Tag Manager, so the numbers you optimise against are the ones your site actually sends. Canonry only reads the configuration; it never changes or publishes it.";function cx({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",m=t.gtm.state==="connected",c=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",p=c||h||t.gtm.state==="unavailable",u={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},y=!i&&!m,v=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:c?u:Wh(t)},{title:"Tag Manager",state:t.gtm.state,ready:m,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?u:Yh(t)}],b=i&&m&&!p?wo(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Xe,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),y?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:lx}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Xe,{text:ix})]}),b&&s?e.jsx(Ye,{type:"button",disabled:r,onClick:()=>s(b.id),children:r?"Working…":b.label}):e.jsx("p",{className:"text-sm text-secondary",children:ox})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:v.map(g=>{const f=g.ready?{label:"Ready",tone:"positive"}:So(g.state),C=g.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:g.title}),e.jsx(oe,{tone:f.tone,children:f.label}),g.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:g.summary}):null,C&&s?C.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(C.id),children:r?"Working…":C.label}):null,g.summary&&g.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":g.changeLabel,disabled:r,onClick:g.onChange,children:"Change"}):null]},g.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function dx({workspace:t=zh,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:m=null,onRetryContracts:c,onRetryEvidence:h,onChangeGoogleAdsSelection:p,onChangeGtmSelection:u,onAddContract:y}){const v=Qh(t),b=Hh(v),g=wo(t),f=t.assessment?.findings??[],C=f.filter(d=>d.outcome!=="pass"),O=f.filter(d=>d.outcome==="pass"),E=C.some(d=>d.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&m===null?e.jsx(cx,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:p,onChangeGtmSelection:u,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(oe,{tone:b.tone,children:b.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Ot(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:b.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(d=>e.jsxs("li",{className:"break-words",children:[rx(d)," ",d.kind,", captured ",Ot(d.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",d.id,")"]})]},d.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?g.id==="review-findings"||g.id==="review-runtime-verification"||g.id==="retry-connection-status"||g.id==="select-contract"||g.id==="retry-integrity"||g.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||g.id==="waiting-for-integrity",onClick:()=>s(g.id),children:n?"Working…":g.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(g.id),children:n?"Working…":g.label}):g.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):v==="runtime-unverified"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:g.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&y?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:y,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:o??"",onChange:d=>i?.(d.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(d=>e.jsx("option",{value:d.id,children:d.name},d.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:tx(t.contract)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Tag Manager"}),e.jsxs("dd",{className:"mt-1 text-sm text-secondary",children:[t.contract.gtm.triggerIds.length," ",t.contract.gtm.triggerIds.length===1?"trigger":"triggers"," and ",t.contract.gtm.variableIds.length," ",t.contract.gtm.variableIds.length===1?"variable":"variables"," required"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Runtime event fields"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:sx(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:$s(t.contract.googleAds.customerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads conversion action"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:$s(t.contract.googleAds.conversionActionId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager container"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:$s(t.contract.gtm.containerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager tag"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:$s(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),m?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:m}),c?e.jsx(P,{type:"button",variant:"outline",onClick:c,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),C.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(oe,{tone:E,children:[C.length," ",C.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:C.map(d=>{const j=ii(d);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:j.label}),e.jsx(oe,{tone:j.tone,children:j.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",d.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",d.code]}),d.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",d.evidenceIds.join(", ")]}):null]},`${d.code}:${d.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Xe,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(d=>{const j=Zh(d.key,v);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${j==="positive"?"bg-positive-fill":j==="caution"?"bg-caution-fill":j==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:d.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:d.detail}),e.jsx(oe,{tone:j,children:ex(d.key,v)})]},d.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[oi({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:p}:{},actionPending:n}),oi({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:u}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&h?e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:d.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:d.kind}),e.jsx("td",{className:"text-secondary",children:Ot(d.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:$s(d.id)})]},d.id))})]})})]}):null,O.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[O.length," ",O.length===1?"passing check":"passing checks"," from the latest assessment"]}),e.jsx("div",{className:"findings-table-wrap mt-3",children:e.jsxs("table",{className:"findings-table",children:[e.jsx("caption",{className:"sr-only",children:"Conversion integrity findings"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Check"}),e.jsx("th",{scope:"col",children:"Result"}),e.jsx("th",{scope:"col",children:"Subject"})]})}),e.jsx("tbody",{children:O.map(d=>{const j=ii(d);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:j.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",d.code]}),d.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",d.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(oe,{tone:j.tone,children:j.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:d.subject})]},`${d.code}:${d.subject}`)})})]})})]}):null,v==="runtime-unverified"?e.jsxs("section",{id:"conversion-integrity-runtime-guidance",className:"page-section-divider","aria-labelledby":"conversion-integrity-runtime-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Runtime verification"}),e.jsx("h3",{id:"conversion-integrity-runtime-title",className:"text-base font-semibold text-heading",children:"Runtime verification checklist"})]})}),e.jsxs("ol",{className:"max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted",children:[e.jsxs("li",{children:["Use a controlled browser session on ",nx(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:$s(t.contract.gtm.tagId)})," fires with ",ax(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:$s(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Ms=3e4,li={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Ct="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",Ht="text-sm font-medium text-secondary";function ci(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:ut(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function qn(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function ux(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Google Ads connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Google Ads OAuth connection is stored for this project.",lastSnapshotAt:null};if(t.status==="selection-required"){const r=t.connection.selection.customerId;return r?{state:"stale",selection:`Selected customer ${r}`,...s,evidence:"A customer is selected, but Canonry needs a fresh conversion-goal observation.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}:{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs a customer account selection.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}const a=t.selectedCustomer;return{state:t.status,selection:a.descriptiveName??`Selected customer ${a.customerId}`,...s,evidence:t.status==="stale"?"The selected customer needs a fresh conversion-goal observation.":"Selected customer and conversion-goal evidence are stored.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}function mx(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function hx(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Tag Manager connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Tag Manager OAuth connection is stored for this project.",lastSnapshotAt:null};const a=t.selection;return t.status==="selection-required"||!a.accountId||!a.containerId?{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs an account and container selection.",lastSnapshotAt:t.connection.lastSnapshotAt}:{state:t.status,selection:mx(a.containerId,a.accountId,a.workspaceId),...s,evidence:t.status==="stale"?"The selected container needs a fresh static configuration observation.":"Selected container configuration evidence is stored.",lastSnapshotAt:t.connection.lastSnapshotAt}}function xx(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:qn(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:qn(t.triggerIds),variableIds:qn(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:qn(t.productionHosts)}}}function di(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function On(t,s,n){if(!s)return null;const a=s.totalAccessible===1?t:`${t}s`;return s.truncated?`Incomplete result: showing ${n} of ${s.totalAccessible} accessible ${a}. Use the CLI or API if the resource is not shown.`:`${s.totalAccessible} accessible ${a} found.`}function Gn(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Fn({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:Ht,children:[s,e.jsx("select",{id:t,className:Ct,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function tn({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function ui({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[m,c]=l.useState(null),h=l.useRef(null),p=l.useRef(null),u=l.useRef(!1);l.useEffect(()=>{const g=u.current;u.current=a,a?p.current?.focus():g&&h.current?.querySelector("button")?.focus()},[a]);function y(){c(null),r(!0)}function v(){c(null),r(!1)}async function b(){i(!0),c(null);try{await n()}catch(g){c(ut(g)),i(!1)}}return e.jsx("div",{ref:h,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(P,{ref:p,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:v,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{b()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),m?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:m}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:y,children:["Disconnect ",t]})})}function mi({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:m,value:c,onChange:h}){const p=n.some(g=>g.id===c),[u,y]=l.useState(!1),v=u||c!==""&&!p&&n.length>0,b=e.jsx("label",{htmlFor:t,className:Ht,children:s});return r?e.jsxs("div",{children:[b,e.jsx("select",{id:t,className:Ct,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[b,e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[b,e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":m})]}):e.jsxs("div",{children:[b,v?e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}):e.jsxs("select",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(g=>e.jsxs("option",{value:g.id,children:[g.name,g.detail?` (${g.detail})`:"",g.active?"":" — inactive"]},g.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{y(!v),h("")},children:v?"Choose from synced list":"Enter an ID manually"})]})}function px({projectId:t,projectName:s}){const n=Qi(),[a,r]=l.useState(null),[o,i]=l.useState(null),[m,c]=l.useState(!1),[h,p]=l.useState(""),[u,y]=l.useState(null),[v,b]=l.useState(!1),[g,f]=l.useState(!1),[C,O]=l.useState(""),[E,A]=l.useState(""),[d,j]=l.useState(""),[S,q]=l.useState(""),[_,N]=l.useState(""),[T,F]=l.useState(!1),[$,H]=l.useState(li),[ve,ue]=l.useState(null),z=l.useRef(null),ee=Ie({...lc({client:V,path:{name:s}}),staleTime:Ms}),re=Ie({...cc({client:V,path:{name:s}}),staleTime:Ms}),W=Ie({...dc({client:V,path:{name:s}}),staleTime:Ms}),K=Ie({...uc({client:V,path:{name:s}}),staleTime:Ms}),R=K.data,se=Ie({...mc({client:V,path:{name:s},query:{limit:5}}),staleTime:Ms}),ce=Ie({...hc({client:V,path:{name:s},query:{limit:5}}),staleTime:Ms}),me=W.data??[],Ae=(ve?me.find(w=>w.id===ve)??null:null)??(me.length===1?me[0]??null:null),B=me.length>1&&!Ae,ae=Ie({...xc({client:V,path:{name:s,contractId:Ae?.id??""}}),enabled:!!Ae,staleTime:Ms}),Ne=Ie({...pc({client:V,path:{name:s}}),enabled:u==="google-ads"&&ee.data?.connected===!0,staleTime:0}),Le=Ie({...gc({client:V,path:{name:s}}),enabled:u==="gtm"&&re.data?.connected===!0,staleTime:0}),Fe=Ie({...fc({client:V,path:{name:s,accountId:d}}),enabled:u==="gtm"&&!!d,staleTime:0}),Pe=Ie({...bc({client:V,path:{name:s,accountId:d,containerId:S}}),enabled:u==="gtm"&&!!d&&!!S,staleTime:0}),Qe=qt(yc({client:V})),he=qt(vc({client:V})),we=qt(jc({client:V})),Ze=qt(Nc({client:V})),_e=qt(wc({client:V})),He=qt(Sc({client:V})),Te=qt(Cc({client:V})),Ce=qt(kc({client:V})),G=qt(Ac({client:V}));l.useEffect(()=>{if(u!=="google-ads"||v||!ee.isSuccess)return;const w=ee.data.connection?.selection;O(w?.customerId??""),A(w?.loginCustomerId??""),b(!0)},[v,ee.data,ee.isSuccess,u]),l.useEffect(()=>{if(u!=="gtm"||g||!re.isSuccess)return;const w=re.data.selection;j(w?.accountId??""),q(w?.containerId??""),N(w?.workspaceId??""),f(!0)},[g,re.data,re.isSuccess,u]),l.useEffect(()=>{!ve||!W.data||W.data.some(w=>w.id===ve)||ue(null)},[W.data,ve]);const M=l.useMemo(()=>{const w=se.data?.snapshots??[],ie=ce.data?.snapshots??[],rt=[...w.map(Kt=>({id:Kt.id,provider:"google-ads",kind:Kt.kind,capturedAt:Kt.capturedAt})),...ie.map(Kt=>({id:Kt.id,provider:"gtm",kind:Kt.kind,capturedAt:Kt.capturedAt}))].sort((Kt,es)=>es.capturedAt.localeCompare(Kt.capturedAt)).slice(0,5),Re=[],gt=ae.data?.googleAdsSnapshot,cs=ae.data?.gtmSnapshot;return gt&&Re.push({id:gt.id,provider:"google-ads",kind:gt.kind,capturedAt:gt.capturedAt}),cs&&Re.push({id:cs.id,provider:"gtm",kind:cs.kind,capturedAt:cs.capturedAt}),{contract:ae.data?.assessment.contract??Ae,assessment:ae.data?.assessment??null,contractSelectionRequired:B,assessmentState:Ae?ae.isError?"unavailable":ae.isLoading?"loading":void 0:void 0,assessmentError:ae.isError?ut(ae.error):null,googleAds:ux(ee.data,ci(se.data?.total??0,se.isLoading,se.isError,se.error),ee.isError),gtm:hx(re.data,ci(ce.data?.total??0,ce.isLoading,ce.isError,ce.error),re.isError),snapshots:rt,assessmentEvidenceSnapshots:Re}},[Ae,B,se.data,se.error,se.isError,se.isLoading,ee.data,ee.isError,ce.data,ce.error,ce.isError,ce.isLoading,re.data,re.isError,ae.data,ae.error,ae.isError,ae.isLoading]),L=l.useSyncExternalStore(Bi,Qn,Qn),je=Object.values(L.runs).some(w=>w.projectId===t&&(w.kind===Ks["google-ads-sync"]||w.kind===Ks["gtm-sync"])),qe=Qe.isPending||he.isPending||we.isPending||Ze.isPending||_e.isPending||He.isPending||Te.isPending||Ce.isPending||G.isPending||je;async function Y(){await Promise.all([ee.refetch(),re.refetch(),W.refetch(),se.refetch(),ce.refetch(),K.refetch(),Ae?ae.refetch():Promise.resolve()])}async function Be(w){await Y();for(let ie=0;ie<10&&!w();ie+=1)await new Promise(rt=>setTimeout(rt,1500)),await Y()}function mt(){const w=document.activeElement;z.current=w instanceof HTMLElement?w:null}function ot(w){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(w);return}globalThis.setTimeout(w,0)}function De(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Oe(w){if(!w)return;!w.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!w.hasAttribute("tabindex")&&(w.tabIndex=-1),w.focus({preventScroll:!0})}function xt(w,ie=w){const rt=document.getElementById(w);rt instanceof HTMLDetailsElement&&(rt.open=!0);const Re=rt?.scrollIntoView;typeof Re=="function"&&Re.call(rt,{behavior:De()?"auto":"smooth",block:"start"}),Oe(document.getElementById(ie)??rt)}function We(w,ie){mt(),ot(()=>xt(w,ie))}function Ve(){const w=z.current;z.current=null,w&&ot(()=>{w.isConnected&&w.focus({preventScroll:!0})})}function $e(){r(null),c(!1),Ve()}function jt(){r(null),y(null),Ve()}function Mt(){r(null),F(!1),Ve()}function Ue(){r(null),y(null),c(!0),We("google-ads-connect-panel","google-ads-connect-title")}function Ge(){r(null),O(""),A(""),b(!1),y("google-ads"),c(!1),We("google-ads-selection-panel","google-ads-selection-title")}function bt(){r(null),j(""),q(""),N(""),f(!1),y("gtm"),c(!1),We("gtm-selection-panel","gtm-selection-title")}function Ke(){r(null),F(!0),We("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Nt(w,ie){Ui({id:w.id,projectId:w.projectId,kind:w.kind,projectLabel:s,sourceAction:ie}),Se({title:ie==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${w.id}`,dedupeMode:"replace"})}async function kt(){rs(n),r(null);try{const w=await Qe.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});p(""),c(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),di(w.authorizationUrl,()=>{Y(),i(null),Ve()})}catch(w){r(ut(w))}}async function yt(){rs(n),r(null);try{const w=await he.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),di(w.authorizationUrl,()=>{Y(),i(null),Ve()})}catch(w){r(ut(w))}}async function At(){if(rs(n),!C){r("Select a Google Ads customer before saving.");return}r(null);try{await we.mutateAsync({path:{name:s},body:{customerId:C,...E.trim()?{loginCustomerId:E.trim()}:{}}}),y(null),Ve(),await Be(()=>ee.data?.selectedCustomer!=null)}catch(w){r(ut(w))}}async function lt(){if(rs(n),!d||!S){r("Select a Tag Manager account and container before saving.");return}r(null);try{await Ze.mutateAsync({path:{name:s},body:{accountId:d,containerId:S,..._?{workspaceId:_}:{}}}),y(null),Ve(),await Be(()=>re.data?.status==="connected")}catch(w){r(ut(w))}}async function U(){rs(n),r(null),await Te.mutateAsync({path:{name:s}}),y(null),c(!1),O(""),A(""),b(!1),i(null),await Y(),Se({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,ot(()=>Oe(document.getElementById("conversion-integrity-title")))}async function ke(){rs(n),r(null),await Ce.mutateAsync({path:{name:s}}),y(null),j(""),q(""),N(""),f(!1),i(null),await Y(),Se({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,ot(()=>Oe(document.getElementById("conversion-integrity-title")))}async function fe(){rs(n),r(null);try{const w=await _e.mutateAsync({path:{name:s}});Nt(w,"google-ads-sync")}catch(w){r(ut(w))}}async function pe(){rs(n),r(null);try{const w=await He.mutateAsync({path:{name:s}});Nt(w,"gtm-sync")}catch(w){r(ut(w))}}async function Lt(){rs(n),r(null);try{const w=await Promise.allSettled([_e.mutateAsync({path:{name:s}}),He.mutateAsync({path:{name:s}})]),[ie,rt]=w;ie.status==="fulfilled"&&Nt(ie.value,"google-ads-sync"),rt.status==="fulfilled"&&Nt(rt.value,"gtm-sync");const Re=w.find(gt=>gt.status==="rejected");if(Re?.status==="rejected")throw Re.reason}catch(w){r(ut(w))}}async function ct(){rs(n);const w=ee.data?.connection?.selection.customerId,ie=re.data?.selection;if(!w||!ie?.accountId||!ie.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const rt=await G.mutateAsync({path:{name:s},body:xx($,w,{accountId:ie.accountId,containerId:ie.containerId})});H(li),F(!1),Ve(),(await W.refetch()).data?.some(gt=>gt.id===rt.id)&&ue(rt.id)}catch(rt){r(ut(rt))}}function Pt(w){switch(w){case"connect-google-ads":Ue();return;case"connect-gtm":mt(),yt();return;case"select-google-ads":Ge();return;case"select-gtm":bt();return;case"sync-google-ads":fe();return;case"sync-gtm":pe();return;case"sync-static-evidence":Lt();return;case"declare-contract":Ke();return;case"review-findings":We("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":We("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Y();return;case"select-contract":We("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ae.refetch();return;case"waiting-for-integrity":return}}const Dt=Ne.data?.customers??[],Jt=Le.data?.accounts??[],Et=Fe.data?.containers??[],ls=Pe.data?.workspaces??[],at=!!C&&!Dt.some(w=>w.customerId===C),ps=!!d&&!Jt.some(w=>w.id===d),wt=!!S&&!Et.some(w=>w.id===S),gs=!!_&&!ls.some(w=>w.id===_),Ft=at&&Ne.isSuccess&&Ne.data.truncated===!1,Zt=ps&&Le.isSuccess&&Le.data.truncated===!1,Vt=wt&&Fe.isSuccess&&Fe.data.truncated===!1,et=gs&&Pe.isSuccess&&Pe.data.truncated===!1,fs=Zt||Vt||et,_t=Zt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Vt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":et?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,St=Gn(Ft,Ne.data,Ne.isError),bs=Gn(Zt,Le.data,Le.isError),dt=Gn(Vt,Fe.data,Fe.isError),ns=Gn(et,Pe.data,Pe.isError),k=Ne.isError?ut(Ne.error):null,be=Le.isError?ut(Le.error):Fe.isError?ut(Fe.error):Pe.isError?ut(Pe.error):null,ye=u==="google-ads"?k:u==="gtm"?be:null,I=On("customer",Ne.data,Dt.length),Q=On("account",Le.data,Jt.length),xe=On("container",Fe.data,Et.length),te=On("draft workspace",Pe.data,ls.length),ne=Le.isError||Fe.isError||Pe.isError&&!!_,Ee=m||u!==null||T;function as(){Ne.refetch()}function pt(){if(Le.isError){Le.refetch();return}if(Fe.isError){Fe.refetch();return}Pe.isError&&Pe.refetch()}return ee.isLoading||re.isLoading||W.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map(w=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"skeleton-text-sm w-full"}),e.jsx("div",{className:"skeleton-text-sm w-3/4"})]},w))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):W.isError&&!W.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",ut(W.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{W.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(dx,{workspace:M,onPrimaryAction:Pt,actionPending:qe,actionError:Ee?null:a,contracts:me,selectedContractId:Ae?.id??null,onSelectContract:w=>ue(w||null),contractError:W.isError?ut(W.error):null,onRetryContracts:()=>{W.refetch()},onRetryEvidence:()=>{Promise.all([se.refetch(),ce.refetch()])},onChangeGoogleAdsSelection:Ge,onChangeGtmSelection:bt,onAddContract:()=>Pt("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,m?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Me(async w=>{w.preventDefault(),await kt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:Ht,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:w=>p(w.target.value),className:Ct,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:Qe.isPending,children:Qe.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:$e,children:"Cancel"})]})]})]}):null,u==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),ye?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ye}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:as,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ft?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(Fn,{id:"google-ads-customer",label:"Customer account",value:C,onChange:w=>{b(!0),O(w);const ie=Dt.find(rt=>rt.customerId===w);A(ie?.parentCustomerId??"")},disabled:Ne.isLoading,children:[e.jsx("option",{value:"",children:Ne.isLoading?"Loading accessible customers…":"Select a customer"}),at?e.jsxs("option",{value:C,disabled:Ft,children:["Saved customer ",C," (",St,")"]}):null,Dt.map(w=>e.jsx("option",{value:w.customerId,children:w.descriptiveName??`Customer ${w.customerId}`},w.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:Ht,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Ct,value:E,onChange:w=>{b(!0),A(w.target.value)},placeholder:"Use only when a manager context is required"})]})]}),I?e.jsx("p",{role:"status",className:`mt-3 text-sm ${Ne.data?.truncated?"text-caution":"text-secondary"}`,children:I}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:we.isPending||Ne.isLoading||Ne.isError||Ft||!C,onClick:Me(At),children:we.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:jt,children:"Cancel"})]}),ee.data?.connected?e.jsx(ui,{providerLabel:"Google Ads",disabled:qe,onDisconnect:U}):null]}):null,u==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),ye?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ye}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:pt,children:Le.isError?"Retry account list":Fe.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,_t?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:_t}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Fn,{id:"gtm-account",label:"Account",value:d,onChange:w=>{f(!0),w!==d&&(q(""),N("")),j(w)},disabled:Le.isLoading,children:[e.jsx("option",{value:"",children:Le.isLoading?"Loading accounts…":"Select an account"}),ps?e.jsxs("option",{value:d,disabled:Zt,children:["Saved account ",d," (",bs,")"]}):null,Jt.map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]}),e.jsxs(Fn,{id:"gtm-container",label:"Container",value:S,onChange:w=>{f(!0),w!==S&&N(""),q(w)},disabled:!d||Fe.isLoading,children:[e.jsx("option",{value:"",children:Fe.isLoading?"Loading containers…":"Select a container"}),wt?e.jsxs("option",{value:S,disabled:Vt,children:["Saved container ",S," (",dt,")"]}):null,Et.map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]}),e.jsxs(Fn,{id:"gtm-workspace",label:"Draft workspace (optional)",value:_,onChange:w=>{f(!0),N(w)},disabled:!S||Pe.isLoading,children:[e.jsx("option",{value:"",children:Pe.isLoading?"Loading workspaces…":"No draft workspace"}),gs?e.jsxs("option",{value:_,disabled:et,children:["Saved draft workspace ",_," (",ns,")"]}):null,ls.map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[Q?e.jsx("p",{role:"status",className:Le.data?.truncated?"text-caution":"text-secondary",children:Q}):null,xe?e.jsx("p",{role:"status",className:Fe.data?.truncated?"text-caution":"text-secondary",children:xe}):null,te?e.jsx("p",{role:"status",className:Pe.data?.truncated?"text-caution":"text-secondary",children:te}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:Ze.isPending||Le.isLoading||Fe.isLoading||Pe.isLoading&&!!_||ne||fs||!d||!S,onClick:Me(lt),children:Ze.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:jt,children:"Cancel"})]}),re.data?.connected?e.jsx(ui,{providerLabel:"Tag Manager",disabled:qe,onDisconnect:ke}):null]}):null,T?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Me(async w=>{w.preventDefault(),await ct()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:Ht,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Ct,value:$.name,onChange:w=>H(ie=>({...ie,name:w.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:Ht,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Ct,value:$.eventName,onChange:w=>H(ie=>({...ie,eventName:w.target.value})),placeholder:"booking_complete"})]}),e.jsx(mi,{id:"contract-conversion-action",label:"Google Ads conversion action",options:R?.googleAds.conversionActions??[],synced:R?.googleAds.syncedAt!=null,loading:K.isLoading,failed:K.isError,onRetry:()=>{K.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:$.conversionActionId,onChange:w=>H(ie=>({...ie,conversionActionId:w}))}),e.jsx(mi,{id:"contract-gtm-tag",label:"Tag Manager tag",options:R?.gtm.tags??[],synced:R?.gtm.syncedAt!=null,loading:K.isLoading,failed:K.isError,onRetry:()=>{K.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:$.tagId,onChange:w=>H(ie=>({...ie,tagId:w}))})]}),e.jsxs("details",{className:"inline-disclosure mt-5 max-w-3xl",children:[e.jsx("summary",{children:"Additional matching rules"}),e.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-conversion-id",className:Ht,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Ct,value:$.conversionId,onChange:w=>H(ie=>({...ie,conversionId:w.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:Ht,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Ct,value:$.conversionLabel,onChange:w=>H(ie=>({...ie,conversionLabel:w.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:Ht,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Ct,value:$.triggerIds,onChange:w=>H(ie=>({...ie,triggerIds:w.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:Ht,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Ct,value:$.variableIds,onChange:w=>H(ie=>({...ie,variableIds:w.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:Ht,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Ct,value:$.campaignIds,onChange:w=>H(ie=>({...ie,campaignIds:w.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:Ht,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Ct,value:$.productionHosts,onChange:w=>H(ie=>({...ie,productionHosts:w.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(tn,{id:"contract-primary-action",checked:$.requirePrimaryAction,onChange:w=>H(ie=>({...ie,requirePrimaryAction:w})),children:"Google Ads action is primary"}),e.jsx(tn,{id:"contract-biddable-goal",checked:$.requireBiddableGoal,onChange:w=>H(ie=>({...ie,requireBiddableGoal:w})),children:"Google Ads goal is biddable"}),e.jsx(tn,{id:"contract-runtime-verification",checked:$.verificationRequired,onChange:w=>H(ie=>({...ie,verificationRequired:w})),children:"Runtime proof is required"}),e.jsx(tn,{id:"contract-transaction-id",checked:$.requireTransactionId,onChange:w=>H(ie=>({...ie,requireTransactionId:w})),children:"Transaction ID is required"}),e.jsx(tn,{id:"contract-value",checked:$.requireValue,onChange:w=>H(ie=>({...ie,requireValue:w})),children:"Conversion value is required"}),e.jsx(tn,{id:"contract-currency",checked:$.requireCurrency,onChange:w=>H(ie=>({...ie,requireCurrency:w})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:G.isPending,children:G.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:Mt,children:"Cancel"})]})]})]}):null]})}const gx=6e4,fx=["7d","14d","30d"],ar="not available",bx='Figures come from the stored Google Ads snapshot; this view never calls Google. The window ends on the newest CLOSED day, because the capture day is only partly recorded and would read as a drop. A calendar day the provider returned no row for is zero delivery, so it is charted as zero. Rates with a zero denominator read "not available", never 0%.',yx="No Google Ads snapshot stored yet",vx="Connect a Google Ads account in Conversion Integrity below, choose the customer, then run a Google Ads sync. Spend, clicks, impressions, and conversions appear here once the first snapshot is stored.",jx="No closed days yet",Nx="The stored snapshot covers no completed day yet. Figures appear after a full day closes in the account time zone; the day a snapshot is captured is partial and is left out on purpose. If this persists, check the latest Google Ads sync in Activity.",wx={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},ws=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Ia=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Co=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),Sx=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function sn(t,s){return t===null||!Number.isFinite(t)?ar:s===null?Sx.format(t/1e6):Iu(t,s)}function Ta(t){if(t===null||!Number.isFinite(t))return ar;const s=t*100;return s>0&&s<.1?"<0.1%":`${Co.format(s)}%`}function Cx(t,s){if(t===null||!Number.isFinite(t))return`${ar} vs prior ${s}d`;if(t===0)return`no change vs prior ${s}d`;const n=Math.abs(t*100),a=n<.1?"<0.1%":`${Co.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function kx(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Ax(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Px(t,s){return s==="none"||t===null||!Number.isFinite(t)||t===0?"text-muted":(s==="up-good"?t>0:t<0)?"text-positive":"text-negative"}function Rx({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=Ie({...Pc({client:V,path:{name:t},query:{window:s}}),staleTime:gx}),i=o.data,m=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Xe,{text:bx})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[$t(i.startDate)," to ",$t(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(ra,{windows:fx,value:s,onChange:n,label:"Google Ads time period"})]});if(o.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[m,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(d=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},d))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(o.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",ut(o.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:c,daily:h,campaigns:p,comparison:u,comparisonUnavailableReason:y,source:v}=i;if(!v){const d=y==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:d?jx:yx}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:d?Nx:vx})]})]})}const b=v.currencyCode,g=v.campaignsInInventory>0&&v.campaignsQueried<v.campaignsInInventory?{queried:v.campaignsQueried,inInventory:v.campaignsInInventory}:null,f=c.costMicros>0&&c.conversions===0,C=[{key:"spend",comparable:!0,label:"Spend",value:sn(c.costMicros,b),change:u?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:Ia.format(c.conversions),change:u?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:f?"no conversions":sn(c.costPerConversionMicros,b),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Ta(c.conversionRate),change:u?.change.conversionRate??null,direction:"up-good",seriesKey:null}],O=[{key:"clicks",label:"Clicks",value:ws.format(c.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:ws.format(c.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Ta(c.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:sn(c.cpcMicros,b),seriesKey:null}],E={costMicros:{label:"Spend",color:nt[1],axisId:"spend",formatValue:d=>sn(d,b)},conversions:{label:"Conversions",color:nt[0],axisId:"conversions",formatValue:d=>Ia.format(d)},clicks:{label:"Clicks",color:nt[2],axisId:"clicks",formatValue:d=>ws.format(d)},impressions:{label:"Impressions",color:nt[3],axisId:"impressions",formatValue:d=>ws.format(d)}},A=[...a].map(d=>({dataKey:d,...E[d]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,g!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",ws.format(g.queried)," of"," ",ws.format(g.inInventory)," campaigns, so they are a subset of the account."]}):null,v.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!u&&y==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:wx["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:C.map(d=>{const j=d.seriesKey!==null&&a.has(d.seriesKey),S=j&&a.size===1,q=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[d.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?E[d.seriesKey].color:"var(--color-mono-600)"}}):null,d.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:d.value}),u&&d.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${Px(d.change,d.direction)}`,children:Cx(d.change,u.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:d.comparable?`no prior ${s} period stored`:" "})]});return d.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:q},d.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:S,onClick:()=>r(_=>{const N=new Set(_);return N.has(d.seriesKey)?N.delete(d.seriesKey):N.add(d.seriesKey),N.size===0?_:N}),className:`rounded-md border px-3 py-2 text-left transition-colors ${j?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:q},d.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:O.map(d=>{const j=d.seriesKey!==null&&a.has(d.seriesKey),S=j&&a.size===1,q=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[d.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:j?E[d.seriesKey].color:"var(--color-mono-600)"}}):null,d.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:d.value})]});return d.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:q},d.key):e.jsx("button",{type:"button","aria-pressed":j,disabled:S,onClick:()=>r(_=>{const N=new Set(_);return N.has(d.seriesKey)?N.delete(d.seriesKey):N.add(d.seriesKey),N.size===0?_:N}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:q},d.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Zi,{data:h,xKey:"date",series:A,xTickFormatter:zs,labelFormatter:$t}),e.jsx("ul",{className:"sr-only",children:h.map(d=>e.jsxs("li",{children:[$t(d.date),":"," ",A.map(j=>`${j.label} ${E[j.dataKey].formatValue(d[j.dataKey])}`).join(", "),d.origin==="filled"?", no delivery reported":""]},d.date))})]}),e.jsxs("div",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:p.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):p.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:d.name??d.campaignId,children:d.name??e.jsx("span",{className:"font-mono text-secondary",children:d.campaignId})}),e.jsx("td",{children:e.jsx(oe,{tone:kx(d.status),children:Ax(d.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ws.format(d.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ws.format(d.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:sn(d.totals.costMicros,b)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ia.format(d.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ta(d.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:d.totals.costMicros>0&&d.totals.conversions===0?e.jsx(oe,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:sn(d.totals.costPerConversionMicros,b)})})]},d.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Ps(xs(v.capturedAt))," · ","customer ",v.customerId," · ","latest closed day ",$t(v.asOfDate),v.openDate?e.jsxs(e.Fragment,{children:[" · ",$t(v.openDate)," still open, excluded"]}):null,v.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",v.timeZone]}):null]})]})]})}const $a=20,ms=50,Ix=50,Tx=50;function rr(t){return t==="viewer"}function ir(t){return t?.status==="unavailable"}function ko(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Ao(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 _n(t,s,n){if(t.kind==="all")return s.map(o=>o.id);if(t.kind==="specific")return s.filter(o=>t.propertyIds.includes(o.id)).map(o=>o.id);const a=new Set(t.groupIds),r=new Set(n.filter(o=>a.has(o.id)).flatMap(o=>o.propertyIds));return s.filter(o=>r.has(o.id)).map(o=>o.id)}function $x(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(r=>s.find(o=>o.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function Ma(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 hi(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function xi(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 Un(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 Xa(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function La(t){return Xa(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Ja({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[m,c]=l.useState(!1),h=o.trim().toLocaleLowerCase(),p=h?t.filter(b=>b.label.toLocaleLowerCase().includes(h)):t,u=m?p:p.slice(0,Ix),y=u.length<p.length;function v(){const b=new Set([...s,...u.map(g=>g.id)]);n(t.filter(g=>b.has(g.id)).map(g=>g.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:o,onChange:b=>i(b.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:u.length===0,onClick:v,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),p.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",u.length," of ",p.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:u.map(b=>{const g=s.includes(b.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${b.label}`,checked:g,type:"checkbox",onChange:f=>n(ko(s,b.id,f.currentTarget.checked))}),e.jsx("span",{children:b.label})]}),b.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[b.urlCount," URLs"]})]},b.id)})}),y?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function or(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function lr({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function Mx({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),m=t.preview,c=m?.counts.needsAttention??0,h=m?.rows.filter(S=>S.status==="matched")??[],p=m?.rows??[],u=p.filter(S=>S.status!=="matched"),y=Math.max(1,Math.ceil(p.length/ms)),v=Math.min(s,y-1),b=p.slice(v*ms,(v+1)*ms),g=Math.max(1,Math.ceil(u.length/ms)),f=Math.min(a,g-1),C=u.slice(f*ms,(f+1)*ms),O=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,E=h.length>0&&!t.isApplying,A=m!==null&&o===m.previewChecksum,d=u.length>0&&f===g-1;l.useEffect(()=>{n(0),r(0),i(null)},[m?.previewChecksum]);async function j(S){if(S)try{t.onCsvChange(await S.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:S=>{j(S.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:S=>t.onCsvChange(S.currentTarget.value),placeholder:`property,group,url
|
|
4
|
+
Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!O,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),m?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[m.counts.matchedRows," matched · ",m.counts.groupsReady," group",m.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),m.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:m.groupChanges.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.label}),e.jsx("td",{className:"text-secondary",children:S.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:S.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[S.addedTargetKeys.length,S.unchangedTargetKeys.length>0?` · ${S.unchangedTargetKeys.length} already members`:""]})]},S.groupKey))})]})}):null,m.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",m.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:b.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:hi(S.status),children:xi(S.status)}),Un(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Un(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",v+1," of ",y," · ",m.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:v===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:v===y-1,onClick:()=>n(S=>Math.min(y-1,S+1)),children:"Next 50 rows"})]})]}):null,c>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",c," row",c===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:C.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:hi(S.status),children:xi(S.status)}),Un(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Un(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",f+1," of ",g]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===0,onClick:()=>r(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===g-1,onClick:()=>r(S=>Math.min(g-1,S+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:A,disabled:t.isApplying||!d,onChange:S=>i(S.currentTarget.checked?m.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!E||!A,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!E,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${m.counts.groupsReady} group${m.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const Lx="—";function Dx({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:m=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:h,onClearQueryAssignments:p,onRemoveQuery:u,onCreateQueries:y,onCreateAndPairQuestions:v,isCreatingQueries:b=!1,createQueriesError:g=null,onManageProjectQueries:f,groups:C,audience:O,onAudienceChange:E,assignmentImpact:A=null,isPreviewingAssignmentImpact:d=!1,assignmentImpactError:j=null,onRetryAssignmentImpact:S,assignmentNotice:q=null,onReplaceAssignments:_,isReplacingAssignments:N=!1,onBack:T,onContinue:F}){const[$,H]=l.useState(""),[ve,ue]=l.useState(!1),[z,ee]=l.useState(!1),[re,W]=l.useState(""),[K,R]=l.useState(""),[se,ce]=l.useState(null);if(ir(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(lr,{message:s.message})});const me=rr(t),X=O,Ae=E,B=_n(X,n,C),ae=B.length,Ne=ae>0&&r.length>0&&!o&&!i&&!d&&A!==null&&j===null,Le=p??u,Fe=$.trim().toLocaleLowerCase(),Pe=Fe?a.filter(L=>La(L).toLocaleLowerCase().includes(Fe)):a,Qe=Pe.filter(L=>(L.propertyIds?.length??0)===0),he=z?Qe:Pe,we=ve?he:he.slice(0,Tx),Ze=we.filter(L=>!Xa(L)),_e=[...new Set(re.split(`
|
|
5
|
+
`).map(L=>L.trim()).filter(Boolean))],He=[...K.matchAll(/\{([a-z][\w-]*)\}/gi)].map(L=>L[1]),Te=n.filter(L=>B.includes(L.id)),Ce=He.length===0||K.trim()===""?[]:Te.map(L=>({propertyId:L.id,text:He.reduce((je,qe)=>je.replaceAll(`{${qe}}`,L.label),K.trim())})),G=[...new Set(Ce.map(L=>L.text))];function M(){const L=new Set([...r,...Ze.map(je=>je.id)]);c(a.filter(je=>L.has(je.id)).map(je=>je.id))}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose queries, then apply them to Properties."})]})}),me?e.jsx(or,{}):null,me?null:e.jsxs("fieldset",{className:"border-y border-default py-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Apply to"}),e.jsx("div",{className:"mt-3 max-w-xl",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"sr-only",children:"Apply to"}),e.jsxs("select",{"aria-label":"Apply to",value:X.kind==="all"?"all":X.kind==="specific"?"specific":`group:${X.groupIds[0]??""}`,onChange:L=>{const je=L.currentTarget.value;je==="all"?Ae({kind:"all"}):je==="specific"?Ae({kind:"specific",propertyIds:[]}):je.startsWith("group:")&&Ae({kind:"groups",groupIds:[je.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),C.length>0?e.jsx("optgroup",{label:"Groups",children:C.map(L=>{const je=_n({kind:"groups",groupIds:[L.id]},n,C).length;return e.jsx("option",{value:`group:${L.id}`,disabled:je===0,children:Ma(L,n)},L.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),X.kind==="groups"?e.jsxs("div",{className:"mt-3 max-w-2xl space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:X.groupIds.map(L=>{const je=C.find(qe=>qe.id===L);return je?e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-sm text-primary",children:[Ma(je,n),e.jsx("button",{type:"button","aria-label":`Remove ${je.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const qe=X.groupIds.filter(Y=>Y!==je.id);Ae(qe.length>0?{kind:"groups",groupIds:qe}:{kind:"all"})},children:"×"})]},je.id):null})}),C.some(L=>!X.groupIds.includes(L.id)&&_n({kind:"groups",groupIds:[L.id]},n,C).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:L=>{L.currentTarget.value&&Ae({kind:"groups",groupIds:[...X.groupIds,L.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),C.filter(L=>!X.groupIds.includes(L.id)).map(L=>{const je=_n({kind:"groups",groupIds:[L.id]},n,C).length;return e.jsx("option",{value:L.id,disabled:je===0,children:Ma(L,n)},L.id)})]})]}):null,ae===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,X.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(Ja,{legend:"Specific Properties",properties:n,selectedPropertyIds:X.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:L=>{Ae({kind:"specific",propertyIds:L})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),me||!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:re,onChange:L=>W(L.currentTarget.value),placeholder:`best apartments in dallas
|
|
6
|
+
luxury apartments atlanta
|
|
7
|
+
pet friendly apartments austin`}),g?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:g}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:_e.length===0||b||i,onClick:()=>{Promise.resolve(y(_e)).then(()=>W(""),()=>{})},children:b?"Adding…":`Add ${_e.length||""} ${_e.length===1?"query":"queries"}`.replace(" "," ")}),f?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:f,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:K,onChange:L=>R(L.target.value),placeholder:"apartments near {property}"}),K.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."]}):Te.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:[G.length," ",G.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:G.slice(0,3).map(L=>e.jsx("li",{className:"text-sm text-strong",children:L},L))}),G.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",G.length-3," more"]}):null]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Ce.length===0||b||i||!v,onClick:()=>{v&&Promise.resolve(v(Ce)).then(()=>R(""),()=>{})},children:b?"Adding…":`Add ${Ce.length||""} ${Ce.length===1?"query":"queries"}`.replace(" "," ")}),Ce.length>0?e.jsxs("p",{className:"mt-2 mb-0 text-sm text-secondary",children:["Each query is measured on the one Property it names, so this adds"," ",Ce.length," assignment",Ce.length===1?"":"s","."]}):null]})]})]}),me?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:Ze.length===0,onClick:M,children:"Select all shown queries"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>c([]),children:"Clear query selection"}),e.jsx(P,{type:"button",size:"sm",className:"min-h-11",disabled:!Ne,onClick:()=>{h({queryIds:r,propertyIds:B,...X.kind==="groups"?{groupIds:X.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${$x(X,C,ae)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[d?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,A?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",A.assignmentCount," Property assignment",A.assignmentCount===1?"":"s"," · ",A.addedAssignments," new, ",A.alreadyPresentAssignments," already assigned"," · ",A.fullRunProviderCalls," provider request",A.fullRunProviderCalls===1?"":"s"," per full run"," · ",A.addedProviderCalls," new",X.kind==="groups"?` · ${A.resolvedPropertyCount} unique ${A.resolvedPropertyCount===1?"Property":"Properties"}${A.overlapCount>0?`, ${A.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):j?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:j}),S?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:S,children:"Retry impact"}):null,T?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:T,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ae," Properties = ",r.length*ae," assignments"]})]}),q?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:q}):null]})}),a.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search queries"}),e.jsx("input",{type:"search",value:$,onChange:L=>{H(L.currentTarget.value),ue(!1)},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",we.length," of ",he.length," queries,"," ",Pe.length-Qe.length," of ",Pe.length," applied"]}),me||Qe.length===0?null:e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{ee(L=>!L),ue(!1)},children:z?"Show all queries":`Show the ${Qe.length} not applied`})]})]}):null,we.length>0?e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[me?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),me?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:we.map(L=>{const je=Xa(L),qe=La(L),Y=r.includes(L.id),Be=(L.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[me?null:je?e.jsx("td",{"aria-hidden":"true"}):e.jsx("td",{className:"p-0",children:e.jsx("label",{className:"flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{"aria-label":`Select query ${qe}`,checked:Y,type:"checkbox",onChange:mt=>c(ko(r,L.id,mt.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:qe})}),e.jsx("td",{className:"text-secondary",children:Ao(L.propertyIds??[],n)}),me?null:e.jsx("td",{className:"text-right",children:Be?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[_?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||N,onClick:()=>ce({queryId:L.id,propertyIds:[...L.propertyIds??[]]}),"aria-label":`Replace query assignments for ${qe}`,children:"Replace assignments"}):null,e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{Le(L.id)},"aria-label":`Clear query assignments for ${qe}`,children:"Clear assignments"})]}):null})]},L.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,me||!se?null:(()=>{const L=a.find(Y=>Y.id===se.queryId),je=L?La(L):"this query",qe=se.propertyIds.filter(Y=>n.some(Be=>Be.id===Y));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",je,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(Ja,{legend:"Properties for this query",properties:n,selectedPropertyIds:qe,onSelectedPropertyIdsChange:Y=>ce(Be=>Be&&{...Be,propertyIds:[...Y]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:N||i,onClick:()=>ce(null),children:"Keep current assignments"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:qe.length===0||N||i||!_,onClick:()=>{_&&Promise.resolve(_({queryId:se.queryId,propertyIds:qe}))},children:N?"Replacing assignments…":`Replace with ${qe.length} ${qe.length===1?"Property":"Properties"}`})]})]})})(),we.length<he.length?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ue(!0),children:"Show all queries"}):null,me?null:e.jsxs(e.Fragment,{children:[m?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${T?"justify-between":"justify-end"}`,children:[T?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:T,children:"Back"}):null,e.jsx(P,{type:"button",variant:Ne?"outline":"default",className:"min-h-11",disabled:!m||i,onClick:F,children:"Continue"})]})]})]})}function Ex({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:m,onEditGroup:c,onRemoveGroup:h,onClearGroupDraft:p,membershipImport:u,onBack:y,onContinue:v}){if(ir(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(lr,{message:s.message})});const b=rr(t),g=r.name.trim().length>0&&r.propertyIds.length>0&&!o,f=n.filter(A=>r.propertyIds.includes(A.id)).length,C=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,O=!b&&(c!==void 0||h!==void 0);function E(){if(p){p();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),b?e.jsx(or,{}):null,b||!u?null:e.jsx(Mx,{value:u}),b?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.name,onChange:A=>i({...r,name:A.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[f," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(Ja,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:A=>i({...r,propertyIds:A})})})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Competitor domains"}),e.jsx("input",{"aria-label":"Competitor domains",className:"mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:r.competitorDomains,onChange:A=>i({...r,competitorDomains:A.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!g,onClick:()=>{m(r)},children:o?"Saving group…":"Save group"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!C,onClick:E,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),C?e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Save this group or clear the form before continuing."}):null]}),e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Competitors"}),O?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:A.name}),e.jsx("td",{className:"text-secondary",children:Ao(A.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:A.competitors.length>0?A.competitors.join(", "):"None"}),O?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[c?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${A.name}`,onClick:()=>c(A),children:"Edit"}):null,h?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${A.name}`,onClick:()=>{h(A.id)},children:"Remove"}):null]})}):null]},A.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,b?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${y?"justify-between":"justify-end"}`,children:[y?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:y,children:"Back"}):null,e.jsx(P,{type:"button",className:"min-h-11",disabled:C,onClick:v,children:a.length===0&&!C?"Continue without groups":"Continue"})]})]})}function qx({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:m=!1,canReviewChanges:c=!0,reviewedChanges:h,reviewChangesError:p,canPublish:u,isPublishing:y=!1,onPublish:v}){const[b,g]=l.useState($a),[f,C]=l.useState($a),[O,E]=l.useState($a);if(ir(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(lr,{message:s.message})});const A=rr(t),d=r?.items??[],j=r?.coverageItems??[],S=d.slice(0,b),q=j.slice(0,f),_=a.slice(0,O),N=i!==void 0,T=h!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),A?e.jsx(or,{}):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,")"]}),d.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:S.map(F=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:F.url}),e.jsx("p",{className:"mt-1 text-secondary",children:F.reason})]},`${F.url}-${F.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",S.length," of ",d.length]}),S.length<d.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>g(F=>F+ms),children:"Show next 50 URLs"}):null]})]}):null,A?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[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,")"]}),q.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[q.map(F=>e.jsxs("section",{"aria-label":`${F.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:F.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:F.savedUrls.map($=>e.jsx("li",{className:"break-all text-secondary",children:$},$))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),F.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:F.currentSitemapUrls.map($=>e.jsx("li",{className:"break-all text-secondary",children:$},$))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},F.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",q.length," of ",j.length]}),q.length<j.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>C(F=>F+ms),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(P,{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??Lx})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,h?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((F,$)=>e.jsx("li",{children:F},`${F}-${$}`))}):null]}):null,e.jsxs("section",{"aria-labelledby":"advanced-measurement-flagged-exceptions-title",className:"space-y-3",children:[e.jsx("h4",{id:"advanced-measurement-flagged-exceptions-title",className:"text-sm font-medium text-heading",children:"Flagged exceptions"}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No flagged exceptions."}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"divide-y divide-default border-y border-default",children:_.map(F=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:F.title}),F.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:F.detail}):null]}),e.jsx(oe,{tone:F.tone??"caution",children:"Needs attention"})]},F.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",_.length," of ",a.length]}),_.length<a.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>E(F=>F+ms),children:"Show next 50 exceptions"}):null]})]})]}),A?null:e.jsxs(e.Fragment,{children:[N&&p?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:p}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${o?"justify-between":"justify-end"}`,children:[o?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!T?e.jsx(P,{type:"button",className:"min-h-11",disabled:m||!c,onClick:()=>{i()},children:m?"Reviewing changes…":"Review changes"}):e.jsx(P,{type:"button",className:"min-h-11",disabled:!u||y,onClick:()=>{v()},children:y?"Publishing setup…":"Publish setup"})]})]})]})}const Ox={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Gx(t){return t.trim().toLocaleLowerCase()}function Fx(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function _x({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 Ux({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const o=!t||r==="reviewing",i=o||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function m(c,h){n({...s,[c]: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(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:c=>{c.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:o,onChange:c=>m("sitemapUrl",c.target.value),placeholder:"https://example.com/sitemap.xml",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:o,onChange:c=>m("examplePropertyUrl",c.target.value),placeholder:"https://example.com/locations/example",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:o,onChange:c=>m("preferredHost",c.target.value),placeholder:"example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:o,onChange:c=>m("propertyPathPattern",c.target.value),placeholder:"/locations/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:o,onChange:c=>m("additionalHost",c.target.value),placeholder:"properties.example.com",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:o,onChange:c=>m("additionalPathPattern",c.target.value),placeholder:"/*",className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:o,onChange:c=>m("excludedPaths",c.target.value),placeholder:"/locations/archive",rows:3,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"}),e.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(P,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Bx({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:m,isContinuing:c=!1,onRetryProperties:h,onReturnToImport:p,maxVisibleProperties:u,onShowAllProperties:y}){const v=Gx(a),b=s.filter(_=>Fx(_,v)),g=Math.max(1,u??b.length),f=b.slice(0,g),C=new Set(o),O=s.filter(_=>C.has(_.id)).map(_=>_.id),E=f.length<b.length;function A(_){const N=new Set(_);i(s.filter(T=>N.has(T.id)).map(T=>T.id))}function d(_,N){if(!t||c)return;const T=new Set(O);N?T.add(_):T.delete(_),A(T)}function j(){!t||c||A([...O,...f.map(_=>_.id)])}function S(){!t||c||i([])}function q(){!t||c||O.length===0||m(O)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||c,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:p,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:a,disabled:c,onChange:_=>r(_.target.value),className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:j,children:"Select all shown"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:c||O.length===0,onClick:S,children:"Clear selection"})]}):null]}),b.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:p,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",f.length," of ",b.length," Properties"]}),e.jsxs("p",{children:[O.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:f.map(_=>{const N=Ox[_.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:_.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(_x,{property:_})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(oe,{tone:N.tone,children:N.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${_.name}`,checked:O.includes(_.id),disabled:c,onChange:T=>d(_.id,T.target.checked),className:"size-6 accent-accent"})})}):null]},_.id)})})]})}),E&&y?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:c,onClick:y,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(P,{type:"button",variant:"ghost",disabled:c,onClick:p,children:"Back"}),e.jsx(P,{type:"button",disabled:c||O.length===0,onClick:q,children:c?"Saving Properties…":"Continue"})]}):null]}):null]})}function Vx(t){return t.activeStep==="import"?e.jsx(Ux,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Bx,{...t})}const Kx=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function zx({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),m=l.useRef(null),c=l.useRef(null),h=l.useRef(null),p=l.useRef(!1),[u,y]=l.useState(!1);return l.useEffect(()=>{s||y(!1)},[s]),l.useEffect(()=>{const v=p.current;p.current=u,u?c.current?.focus():v&&h.current?.focus()},[u]),l.useEffect(()=>{const v=i.current;if(i.current=t,v===null||v===t)return;const b=m.current?.querySelector('h1, h2, h3, [role="heading"]');b&&(b.tabIndex=-1,b.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(oe,{tone:"caution",children:"Unpublished changes"}),n&&a?u?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(P,{ref:c,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>y(!1),children:"Keep editing"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(P,{ref:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>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:Kx.map(v=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===v.id?"step":void 0,onClick:()=>r(v.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===v.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:v.label}):e.jsx("span",{"aria-current":t===v.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===v.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:v.label})},v.id))})}),e.jsx("div",{ref:m,children:o})]})}function Qx(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Vx,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(Dx,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Ex,{...t.groups,access:s}):"review"in t?e.jsx(qx,{...t.review,access:s}):null}function Bn(t){return e.jsx(zx,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Qx(t)})}function Po(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function It(t){return{"If-Match":t,"Idempotency-Key":Po()}}function Ls(t){return t instanceof dn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function Qt(t,s){return t instanceof dn?s:(t instanceof Error?t.message.trim():"")||s}function Hx(t){const s="Could not calculate assignment impact.";if(!(t instanceof dn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Wx={loadSetup:t=>it(()=>Yc({client:V,path:{name:t}})),loadDraft:t=>it(()=>Wc({client:V,path:{name:t}})),createDraft:(t,s)=>it(()=>Hc({client:V,path:{name:t},headers:{"Idempotency-Key":Po()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>it(()=>Qc({client:V,path:{name:t},headers:It(s),body:n})),applySitemapSelection:(t,s,n,a)=>it(()=>zc({client:V,path:{name:t},headers:It(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>it(()=>Kc({client:V,path:{name:t},body:s})),applyAssignments:(t,s,n)=>it(()=>Vc({client:V,path:{name:t},headers:It(s),body:n})),replaceAssignments:(t,s,n)=>it(()=>Bc({client:V,path:{name:t},headers:It(s),body:n})),applyPairedAssignments:(t,s,n)=>it(()=>Uc({client:V,path:{name:t},headers:It(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>it(()=>_c({client:V,path:{name:t},headers:It(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>it(()=>Fc({client:V,path:{name:t},headers:It(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>it(()=>Gc({client:V,path:{name:t},headers:It(s),body:{target:n}})),upsertGroup:(t,s,n)=>it(()=>Oc({client:V,path:{name:t},headers:It(s),body:{group:n}})),removeGroup:(t,s,n)=>it(()=>qc({client:V,path:{name:t},headers:It(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>it(()=>Ec({client:V,path:{name:t},headers:It(s),body:n})),removeCompetitor:(t,s,n,a)=>it(()=>Dc({client:V,path:{name:t},headers:It(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>it(()=>Lc({client:V,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>it(()=>Mc({client:V,path:{name:t},headers:It(s),body:n})),compilePreview:t=>it(()=>$c({client:V,path:{name:t}})),diffPreview:t=>it(()=>Tc({client:V,path:{name:t}})),publish:(t,s,n)=>it(()=>Ic({client:V,path:{name:t},headers:It(s),body:n})),discard:(t,s)=>it(()=>Rc({client:V,path:{name:t},headers:It(s)}))},pi={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},fn={name:"",propertyIds:[],competitorDomains:""},gi=50;function vn(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Yx(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 fi(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(i=>i==="*"||i==="{slug}").length!==1||r.some(i=>i.includes("*")&&i!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(i=>i==="*"?"{slug}":i).join("/")}`}const n=t.examplePropertyUrl.trim();if(!n)throw new Error("Add one example Property page so Canonry can identify the matching URLs.");try{const a=new URL(n).pathname.split("/").filter(Boolean);if(a.length===0)throw new Error;return a[a.length-1]="{slug}",`/${a.join("/")}`}catch{throw new Error("Example Property page must be a valid web address.")}}function Xx(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,m=i.startsWith("*"),c=i.endsWith("*"),h=i.slice(m?1:0,c?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const p=m&&c?"contains":m?"suffix":c?"prefix":"exact",u=`${p}:${h}`;n.has(u)||(n.add(u),s.push({kind:p,value:h}))}return s}function Jx(t){const s=Yx(t.sitemapUrl),n=t.examplePropertyUrl.trim()?vn(t.examplePropertyUrl):null,a=vn(t.preferredHost)??n??vn(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=vn(t.additionalHost),o=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(o!==i||o&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const m=Xx(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:fi(t)},...r?{aliases:[{host:r,pathTemplate:fi({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...m.length>0?{excludedSlugPatterns:m}:{}}}}function Zx(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 ep(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 bi(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function tp(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Da(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Za(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function yi(t){return vn(t)}function Ro(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 Io(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 To(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function $o(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function sp(t,s){const n=Ro(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const o=n.urlMatchers[r];return o?`${n.label} — ${o}`:n.label}if(a==="aliases"&&typeof r=="number"){const o=n.aliases[r];return o?`${n.label} — ${o}`:n.label}return n.label}function np(t,s){const n=Io(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const o=n.competitors.at(r)?.domain;return o?`${n.label} — ${o}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const o=$o(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function ap(t,s){const n=To(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${$o(t.authoring,n.targetKey)} — ${a}`}function rp(t,s){return s.path[0]==="identities"?"Project domain":sp(t,s)??np(t,s)??ap(t,s)}function vi(t,s,n){const a=To(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},o=s.path.at(-1);if(n==="models"&&typeof o=="string")return r.models?.[o];if(n==="locations"&&typeof o=="number")return r.locations?.[o]}function ip(t,s){const n=rp(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,vi(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,vi(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 Vn(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function Mo(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 op(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${Vn(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${Vn(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${Vn(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${Vn(n,"item")} need review.`:s}})()}${Mo(a)}`}function lp(t,s){const n=new Map;for(const a of t){const r=ip(a,s),o=[a.ruleId,a.severity,r.title,r.detail].join("\0"),i=n.get(o)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};i.paths.add(JSON.stringify(a.path)),r.affected&&i.affected.add(r.affected),n.set(o,i)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:op(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function Ea(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function qa(t,s,n){const a=Ro(n,t.path),r=Io(n,t.path),o=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=o?n?.targets.find(p=>p.stableKey===o):void 0,m=a?.label??r?.label,c=Mo(m?[m]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${c}`};case"excluded-target-has-assignments":return{...h,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${c}`};case"group-unknown-target":return{...h,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${c}`};case"measurement.discovery.proposed_new_target":{const p=Ea(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${p}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const p=Ea(a)??"the proposed Property",u=i?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${p}. It may be the same Property as ${u}.`}}case"measurement.discovery.rebind_ambiguous":{const p=Ea(a)??"the proposed Property",u=i?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${p}. It may match ${u}; choose the correct Property.`}}default:return{...h,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function cp(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,r=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,o=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),o>0&&n.push(`${o} query assignment ${o===1?"change":"changes"}`),r>0&&n.push(`${r} group ${r===1?"change":"changes"}`),s&&n.unshift("Existing results remain visible after you publish this setup."),{title:s?"Historical results will be kept":t.activeRevision===null?"New setup ready":"Changes ready",items:n.length>0?n:["No changes from the published setup."]}}function is(t){return[...new Set(t)]}function As(t){return is(t).sort()}function dp(t,s,n){return t.kind==="groups"?{groupKeys:As(t.groupIds),queryIds:As(n)}:{targetKeys:As(t.kind==="all"?s:t.propertyIds),queryIds:As(n)}}function up(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 ji(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function mp(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(ji).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(ji).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:Za(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function hp({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:m,onManageProjectQueries:c,onPublished:h,service:p=Wx}){const[u,y]=l.useState(null),[v,b]=l.useState(null),[g,f]=l.useState("import"),[C,O]=l.useState(!0),[E,A]=l.useState(null),[d,j]=l.useState(null),[S,q]=l.useState([]),[_,N]=l.useState({...pi}),[T,F]=l.useState("idle"),[$,H]=l.useState(""),[ve,ue]=l.useState(gi),[z,ee]=l.useState([]),[re,W]=l.useState([]),[K,R]=l.useState({kind:"all"}),[se,ce]=l.useState(null),[me,X]=l.useState(null),[Ae,B]=l.useState(!1),[ae,Ne]=l.useState(null),[Le,Fe]=l.useState(0),[Pe,Qe]=l.useState(null),[he,we]=l.useState({...fn}),[Ze,_e]=l.useState(null),[He,Te]=l.useState(""),[Ce,G]=l.useState(null),[M,L]=l.useState(!1),[je,qe]=l.useState(!1),[Y,Be]=l.useState(null),[mt,ot]=l.useState(null),[De,Oe]=l.useState(null),[xt,We]=l.useState(null),[Ve,$e]=l.useState(null),jt=l.useRef(0),Mt=l.useRef(0),Ue=v?.draft??null,Ge=v?.etag??null,bt=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:mp(o)}:null,[i,o]),Ke=Ue??bt;async function Nt(I){const Q=++jt.current;O(!0),A(null);try{let[xe,te]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);if(!te.draft&&I&&i&&(await p.createDraft(t,xe.activeRevision),[xe,te]=await Promise.all([p.loadSetup(t),p.loadDraft(t)])),Q!==jt.current)return;y(xe),b(te),f(Zx(te.draft));const ne=Da(te.draft);ee(ne)}catch(xe){if(Q!==jt.current)return;A(Qt(xe,"Could not load advanced measurement setup."))}finally{Q===jt.current&&O(!1)}}l.useEffect(()=>(Nt(!0),()=>{jt.current+=1}),[t,i,p]),l.useEffect(()=>{!C&&!Ue&&bt&&f("properties")},[Ue,C,bt]);async function kt(){const I=await p.loadDraft(t);return b(I),I}async function yt(I){$e(null);try{const[Q,xe]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);y(Q),b(xe);const te=Da(xe.draft);ee(te),f(ne=>ep(xe.draft,ne)),j(I)}catch(Q){j(Qt(Q,I))}}async function At(I,Q,xe,te={}){const{preserveBusyAction:ne=!1}=te;if(!i||!Ge||De&&!ne)return null;ne||Oe(I),j(null),$e(null);try{const Ee=await Q(Ge),as=await kt();return q((Ee.warnings??[]).map((pt,Js)=>qa(pt,Js,as.draft?.authoring))),as}catch(Ee){return Ls(Ee)?await yt("This setup changed in another session. The latest draft is loaded; review your changes again."):j(Qt(Ee,xe)),null}finally{ne||Oe(null)}}const lt=l.useMemo(()=>(Ke?.authoring.targets??[]).map(I=>{const Q=bi(I);return{id:I.stableKey,name:I.label,url:Q[0]??"No URL",urls:Q,state:tp(I.status)}}),[Ke]),U=l.useMemo(()=>Ke?.authoring.targets.filter(I=>I.status==="included")??[],[Ke]),ke=l.useMemo(()=>U.map(I=>({id:I.stableKey,label:I.label,urlCount:bi(I).length})),[U]),fe=Ke?.authoring.assignments.length??0,pe=l.useMemo(()=>{if(!Ke)return[];const I=new Set(s.map(te=>te.id)),Q=s.map(te=>({id:te.id,text:te.query,source:"saved-project-queries",propertyIds:is(Ke.authoring.assignments.filter(ne=>ne.queryId===te.id).map(ne=>ne.targetKey))})),xe=is(Ke.authoring.assignments.map(te=>te.queryId).filter(te=>!I.has(te))).map(te=>({id:te,source:"unavailable-tracked-query",state:"missing",propertyIds:is(Ke.authoring.assignments.filter(ne=>ne.queryId===te).map(ne=>ne.targetKey))}));return[...Q,...xe]},[s,Ke]),Lt=l.useMemo(()=>(Ke?.authoring.groups??[]).map(I=>({id:I.stableKey,name:I.label,propertyIds:I.targetKeys,competitors:I.competitors.map(Q=>Q.domain)})),[Ke]),ct=l.useMemo(()=>{if(re.length===0)return null;const I=dp(K,ke.map(xe=>xe.id),re);return(I.groupKeys?.length??I.targetKeys?.length??0)>0?I:null},[K,ke,re]),Pt=ct?JSON.stringify(ct):"";l.useEffect(()=>{const I=ct,Q=++Mt.current;if(!i||!Ue||!Ge||!I){ce(null),X(null),Ne(null),B(!1);return}ce(null),X(null),Ne(null),B(!0);const xe=window.setTimeout(()=>{p.previewAssignments(t,I).then(te=>{if(Q===Mt.current){if(te.draftEtag!==Ge){ce(null),X(null),Ne("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}ce(te),X(Pt)}}).catch(te=>{Q===Mt.current&&(ce(null),X(null),Ne(Hx(te)))}).finally(()=>{Q===Mt.current&&B(!1)})},250);return()=>{window.clearTimeout(xe),Mt.current+=1}},[ct,Pt,Le,i,Ue,Ge,t,p]);const Dt=l.useMemo(()=>[...fe===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...Ke?.authoring.assignments.some(I=>I.queryClass==="unclassified")&&!(bt&&o?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...S],[fe,bt,o,S,Ke]),Jt=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 Et(I){let Q;try{Q=Jx(I)}catch(te){j(Qt(te,"Check the sitemap details and try again."));return}N(I),F("reviewing");const xe=await At("import",te=>p.importSitemap(t,te,Q),"Could not review this sitemap.");if(xe?.draft){const te=xe.draft.authoring.targets.filter(Ee=>Ee.status==="proposed").map(Ee=>Ee.stableKey),ne=xe.draft.authoring.targets.filter(Ee=>Ee.status==="included").map(Ee=>Ee.stableKey);ee([...ne,...te]),H(""),ue(gi),f("properties"),F("idle")}else F("error")}async function ls(I){if(!m||I.length===0||De)return[];Oe("create-queries"),We(null);try{return await m(I)}catch(Q){throw We(ut(Q)),Q}finally{Oe(null)}}async function at(I){if(!Ue||!Ge||De)return;const Q=new Set(I),te=Ue.authoring.targets.filter(Ee=>Ee.status==="proposed"&&Ee.discoveryIdentity).map(Ee=>({discoveryIdentity:Ee.discoveryIdentity,action:Q.has(Ee.stableKey)?"create":"ignore"})),ne=te.length>0||Ue.authoring.targets.some(Ee=>Ee.status!=="proposed"&&Ee.status==="included"!==Q.has(Ee.stableKey));Oe("properties"),j(null),$e(null);try{if(!ne){ee([...Q]),R({kind:"all"}),f("groups");return}await p.applySitemapSelection(t,Ge,te,[...Q]);const Ee=await kt(),as=Da(Ee.draft);ee(as),R({kind:"all"}),f("groups")}catch(Ee){Ls(Ee)?await yt("This setup changed in another session. The latest Properties are loaded."):j(Qt(Ee,"Could not save the selected Properties."))}finally{Oe(null)}}async function ps(I){const Q=I.groupIds&&I.groupIds.length>0?{groupKeys:As(I.groupIds),queryIds:As(I.queryIds)}:{targetKeys:As(I.propertyIds),queryIds:As(I.queryIds)};if(!se||me!==JSON.stringify(Q)||!Ge||se.draftEtag!==Ge){j("Review the latest assignment impact before assigning queries.");return}await At("assignments",te=>p.applyAssignments(t,te,Q),"Could not apply these queries.")&&(W([]),Qe(`${se.assignments.added} new assignment${se.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function wt(I){if(I.propertyIds.length===0)return;await At("replace-assignments",xe=>p.replaceAssignments(t,xe,{targetKeys:is(I.propertyIds),queryIds:[I.queryId]}),"Could not replace this query assignment.")&&(W(xe=>xe.filter(te=>te!==I.queryId)),Qe("Query assignments replaced."))}async function gs(I,Q=!1){if(I.length===0)return;if(!await At("paired-assignments",te=>p.applyPairedAssignments(t,te,[...I]),"Could not assign these queries.",{preserveBusyAction:Q}))throw new Error("Could not assign these queries.")}async function Ft(I){if(!(!i||!m||I.length===0||De)){Oe("create-and-pair-questions"),We(null);try{let Q;try{Q=await m(is(I.map(ne=>ne.text)))}catch(ne){throw We(ut(ne)),ne}const xe=new Map(Q.map(ne=>[ne.query,ne.id])),te=I.map(ne=>({targetKey:ne.propertyId,queryId:xe.get(ne.text)})).filter(ne=>ne.queryId!==void 0);if(te.length!==I.length){const ne=new Error("The created queries could not be matched to their Properties.");throw We("The queries were added, but could not be paired with every Property. Try again to pair them."),ne}try{await gs(te,!0)}catch(ne){throw We("The queries were added, but could not be assigned to their Properties. Try again to pair them."),ne}}finally{Oe(null)}}}async function Zt(I){if(!Ue)return;const Q=is(Ue.authoring.assignments.filter(te=>te.queryId===I).map(te=>te.targetKey));if(Q.length===0)return;await At(`remove-${I}`,te=>p.removeAssignment(t,te,Q,I),"Could not clear this query assignment.")&&W(te=>te.filter(ne=>ne!==I))}async function Vt(I){if(!Ue||!Ge||De)return;const Q=I.name.trim();if(!Q)return;const xe=Ze??Za(Q,"group"),te=Ue.authoring.groups.find(pt=>pt.stableKey===xe);if(te&&Ze===null){j(`A group named "${te.label}" already exists. Edit it or choose a different name.`);return}const ne=I.competitorDomains.split(/[\s,]+/).map(pt=>pt.trim()).filter(Boolean),Ee=ne.find(pt=>yi(pt)===null);if(Ee){j(`"${Ee}" is not a valid competitor domain.`);return}const as=is(ne.map(pt=>yi(pt)));Oe("group"),j(null),$e(null);try{const pt=await p.upsertGroup(t,Ge,{stableKey:xe,label:Q,targetKeys:is(I.propertyIds),competitors:as.map(w=>te?.competitors.find(ie=>ie.domain===w)??{stableKey:Za(w,"competitor"),label:w,domain:w,aliases:[]})}),Js=await kt();q(pt.warnings.map((w,ie)=>qa(w,ie,Js.draft?.authoring))),we({...fn}),_e(null)}catch(pt){Ls(pt)?await yt("This setup changed in another session. The latest groups are loaded."):j(Qt(pt,"Could not save this group."))}finally{Oe(null)}}function et(I){const Q=Ue?.authoring.groups.find(xe=>xe.stableKey===I);Q&&(_e(I),we({name:Q.label,propertyIds:[...Q.targetKeys],competitorDomains:Q.competitors.map(xe=>xe.domain).join(", ")}))}async function fs(I){await At("remove-group",xe=>p.removeGroup(t,xe,I),"Could not remove this group.")&&(R(xe=>xe.kind==="groups"&&xe.groupIds.includes(I)?{kind:"all"}:xe),Ze===I&&(_e(null),we({...fn})))}function _t(I){Te(I),G(null),Be(null),ot(null)}async function St(){if(!(!i||!He.trim()||M||je)){L(!0),Be(null),ot(null);try{G(await p.previewGroupMembership(t,{csv:He}))}catch(I){G(null),Be(Qt(I,"Could not review this CSV."))}finally{L(!1)}}}async function bs(I){if(!(!i||!Ge||!Ce||I.length===0||De)){if(Ce.draftEtag!==Ge){Be("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}qe(!0),Oe("group-import"),Be(null),ot(null),$e(null);try{const Q=await p.applyGroupMembership(t,Ge,{csv:He,sourceChecksum:Ce.sourceChecksum,previewChecksum:Ce.previewChecksum,acceptedRows:is(I.map(String)).map(Number)}),xe=await kt();q(Q.warnings.map((te,ne)=>qa(te,ne,xe.draft?.authoring))),Te(""),G(null),ot(`${Q.addedMemberships} membership${Q.addedMemberships===1?"":"s"} added${Q.unchangedMemberships>0?`; ${Q.unchangedMemberships} already present`:""}.`)}catch(Q){Ls(Q)?(await yt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Be("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Be(Qt(Q,"Could not apply this CSV."))}finally{Oe(null),qe(!1)}}}async function dt(){if(!(!Ue||!Ge||De||fe===0)){Oe("review"),j(null),$e(null);try{const[I,Q]=await Promise.all([p.compilePreview(t),p.diffPreview(t)]),xe=[...I.checks,...Q.checks],te=xe.some(ne=>ne.ruleId==="active-revision-schema-v1");if(q(lp(xe.filter(ne=>ne.ruleId!=="active-revision-schema-v1"),{authoring:Ke?.authoring,queries:s})),!I.ok||!Q.ok)return;if(Q.diff.activeRevision!==Ue.baseActiveRevision){await yt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(I.compiledChecksum!==Q.compiledChecksum){j("The setup changed while it was being reviewed. Review the latest changes again.");return}$e({etag:Ge,baseActiveRevision:Ue.baseActiveRevision,compiledChecksum:I.compiledChecksum,changes:cp(Q.diff,te),providerCalls:I.plan.executionNodes.reduce((ne,Ee)=>ne+Ee.expectedSnapshots,0)})}catch(I){j(Qt(I,"Could not review this setup."))}finally{Oe(null)}}}async function ns(){if(!(!Ue||!Ge||!Ve||De)){if(Ge!==Ve.etag||Ue.baseActiveRevision!==Ve.baseActiveRevision){$e(null),j("The setup changed after review. Review the latest changes before publishing.");return}Oe("publish"),j(null);try{await p.publish(t,Ge,{expectedActiveRevision:Ve.baseActiveRevision,expectedCompiledChecksum:Ve.compiledChecksum}),b({draft:null,etag:null}),$e(null),h?.()}catch(I){Ls(I)?await yt("The setup changed before it could be published. Review the latest draft and publish again."):j(Qt(I,"Could not publish this setup."))}finally{Oe(null)}}}async function k(){if(!(!Ge||De)){Oe("discard"),j(null);try{await p.discard(t,Ge),b({draft:null,etag:null}),$e(null),h?.()}catch(I){Ls(I)?await yt("This setup changed in another session. The latest draft is loaded."):j(Qt(I,"Could not discard these changes."))}finally{Oe(null)}}}async function be(){if(!(!Ue||!Ge||!u||De)){Oe("restart"),j(null),$e(null);try{await p.discard(t,Ge),await p.createDraft(t,u.activeRevision),N({...pi}),H(""),ee([]),W([]),R({kind:"all"}),ce(null),Ne(null),Qe(null),we({...fn}),_e(null),Te(""),G(null),Be(null),ot(null),await Nt(!1)}catch(I){Ls(I)?await yt("The setup changed again. Reloaded the latest draft and published setup."):j(Qt(I,"Could not restart this setup."))}finally{Oe(null)}}}if(C)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if(E)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:E}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Nt(!0)},children:"Try again"})]})]});if(!Ke||i&&!Ge)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-empty-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-empty-title",children:"Advanced measurement setup"})}),e.jsx("p",{className:"text-sm text-secondary",children:i?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(i&&Ue&&u&&Ue.baseActiveRevision!==u.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:De==="restart",onClick:()=>{be()},children:De==="restart"?"Restarting…":"Discard draft and restart"})]}),d?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:d}):null]});const ye=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(P,{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:[u?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,d?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:d}):null,ye,g==="import"||g==="properties"?e.jsx(Bn,{currentStep:g,hasDraft:Ue!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{k()},importProperties:{importDraft:_,onImportDraftChange:I=>{N(I),F("idle"),j(null)},onReviewSitemap:I=>{Et(I)},reviewState:T,properties:lt,propertiesState:"ready",propertiesSearch:$,onPropertiesSearchChange:H,maxVisibleProperties:ve,onShowAllProperties:()=>ue(lt.length),selectedPropertyIds:z,onSelectedPropertyIdsChange:I=>ee([...I]),onContinue:I=>{at(I)},isContinuing:De==="properties",onRetryProperties:()=>{kt()},onReturnToImport:()=>f("import")}}):g==="queries"?e.jsx(Bn,{currentStep:"queries",hasDraft:Ue!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{k()},onManageProjectQueries:c,queries:{onCreateQueries:m?I=>ls(I):void 0,isCreatingQueries:De==="create-queries"||De==="create-and-pair-questions",isBusy:De!==null,createQueriesError:xt,availability:Jt,properties:ke,queries:pe,selectedQueryIds:re,isApplying:De==="assignments"||De==="paired-assignments",onSelectedQueryIdsChange:I=>W([...I]),onApplySelectedQueries:I=>ps(I),groups:Lt,audience:K,onAudienceChange:I=>{R(I),Qe(null)},assignmentImpact:se&&me===Pt?up(se):null,isPreviewingAssignmentImpact:Ae,assignmentImpactError:ae,onRetryAssignmentImpact:()=>Fe(I=>I+1),assignmentNotice:Pe,onReplaceAssignments:wt,isReplacingAssignments:De==="replace-assignments",onCreateAndPairQuestions:i&&m?Ft:void 0,onClearQueryAssignments:Zt,onRemoveQuery:Zt,canContinue:fe>0,onBack:()=>f("groups"),onContinue:()=>f("review")}}):g==="groups"?e.jsx(Bn,{currentStep:"groups",hasDraft:Ue!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{k()},groups:{properties:ke,groups:Lt,groupDraft:he,isSaving:De==="group",onGroupDraftChange:we,onSaveGroup:Vt,onEditGroup:I=>et(I.id),onRemoveGroup:fs,onClearGroupDraft:()=>{_e(null),we({...fn})},membershipImport:{csv:He,preview:Ce,isReviewing:M,isApplying:je,error:Y,notice:mt,onCsvChange:_t,onReview:St,onApply:bs},onBack:()=>{f("properties")},onContinue:()=>f("queries")}}):e.jsx(Bn,{currentStep:"review",hasDraft:Ue!==null,canEdit:i,onStepChange:i?void 0:f,onDiscard:()=>{k()},review:{counts:{properties:U.length,queries:new Set(Ke.authoring.assignments.map(I=>I.queryId)).size,groups:Ke.authoring.groups.length,assignments:Ke.authoring.assignments.length,providerCalls:Ve?.providerCalls},flaggedExceptions:Dt,reviewedChanges:Ve?.changes,isReviewing:De==="review",canReviewChanges:fe>0&&!De,onReviewChanges:dt,onBack:()=>f("queries"),canPublish:Ve!==null&&!De,isPublishing:De==="publish",onPublish:ns}})]})}const xp=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function Ni(t){return t.label!=="Complete"}const Ds="__all_properties__",pp=50,Lo=50,gp=20,fp=50,bp=250,yp=5,vp=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],jp={"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"},Do={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."},Np={numerator:null,denominator:null,reason:"plan_v1"};function wn(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 wp(t){return wn(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function Eo(t){if(wn(t))return"";const s=t.reason??"unavailable";return Do[s]??s}function wi(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 Sp(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function Cp(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function kp(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function jn({metric:t,compact:s=!1}){const n=s?wn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":wn(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",...wn(t)?{}:{title:Eo(t)},children:e.jsx("span",{className:n,children:wp(t)})})}function cr({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(P,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function Si({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(Lo),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((m,c)=>e.jsx("li",{className:a,children:m},`${m}:${c}`))}),e.jsx(cr,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function Ap({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(Lo),o=t.slice(0,a);return e.jsxs("section",{"aria-label":"Evidence",children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:"Evidence"}),s==="loading"?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Loading evidence…"}):s==="error"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsx("span",{children:"Evidence could not be loaded."}),n?e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:o.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(oe,{tone:i.tone,children:jp[i.kind]}),i.historical?e.jsx(oe,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(cr,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function Pp({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(Si,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(Si,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(Ap,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function Rp({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(jn,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function Ci({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const m=n.findIndex(p=>p.value===s);let c=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?c=(m+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?c=(m-1+n.length)%n.length:i.key==="Home"?c=0:i.key==="End"&&(c=n.length-1),c===null)return;i.preventDefault();const h=n[c];a(h.value),i.currentTarget.querySelectorAll('[role="radio"]')[c].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const m=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":m,tabIndex:m?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${m?"segmented-option-active":""}`,children:i.label},i.value)})})}function Ip({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(Xe,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function Tp({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:m=!1,isLoadMoreError:c=!1,viewSearch:h,onViewChange:p,onLoadMore:u,onPropertyExpand:y,onRetryEvidence:v,renderPropertyLink:b}){const g=t.currentView!=null,f=t.classReporting==="available"&&(g||t.classScopes!=null),[C,O]=l.useState(t.currentView?.queryClass??"all"),[E,A]=l.useState(t.currentView?.scope.key??Ds),[d,j]=l.useState(h??""),[S,q]=l.useState(pp),[_,N]=l.useState(gp),[T,F]=l.useState(t.currentView?.sort??"label-asc"),[$,H]=l.useState(null),ve=l.useRef(h??""),ue=f&&!g&&C!=="all"?C==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,z=g?{aggregate:t.currentView.aggregate,groups:[]}:ue,ee=l.useCallback(G=>{if(!g||!p)return;const M=G.scope??(E===Ds?"all":"group"),L=G.search??d;ve.current=L,p({scope:M,...M==="group"?{groupKey:G.groupKey??E}:{},queryClass:G.queryClass??C,...L?{search:L}:{},...G.sort?{sort:G.sort}:{}})},[p,d,C,E,g]);l.useEffect(()=>{!t.currentView||i||(O(t.currentView.queryClass),A(t.currentView.scope.key??Ds),t.currentView.sort&&F(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{h!==void 0&&(ve.current=h,j(G=>G.trim()===h.trim()?G:h))},[h]),l.useEffect(()=>{if(!g||!p||d===ve.current)return;const G=window.setTimeout(()=>ee({search:d}),bp);return()=>window.clearTimeout(G)},[p,ee,d,g]);const re=t.availableGroups??z.groups;l.useEffect(()=>{E===Ds||re.some(G=>G.id===E)||A(Ds)},[re,E]);const W=g?void 0:z.groups.find(G=>G.id===E),K=W?.aggregate??z.aggregate,R=G=>f?G:Np,se=T,ce=d.trim().toLocaleLowerCase(),me=l.useMemo(()=>!g&&ce?K.properties.filter(G=>G.name.toLocaleLowerCase().includes(ce)):K.properties,[K.properties,ce,g]),X=g?me:me.slice(0,S),Ae=(g?t.currentView?.scope.kind==="group":W!=null)&&C==="non-brand"&&f&&(g||W.confirmedCompetitorCount>0)&&(K.shareOfVoice?.length??0)>0,B=f?K.unavailablePropertyCount??0:0,ae=t.flaggedResults.reduce((G,M)=>G+(M.count??1),0),Ne=t.flaggedResultsTotal??ae,Le=[R(K.metrics.propertiesMentioned),R(K.metrics.mentionCoverage),R(K.metrics.citationCoverage)].map(Eo).find(Boolean),Fe=f?t.nextActionText??Le??(B>0?`${B} ${B===1?"property is":"properties are"} unavailable.`:Ne>0?`${Ne} flagged ${Ne===1?"result needs":"results need"} review.`:null):Do.plan_v1,he=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?Sp(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,we=Cp(t.latestMeasurement.date),Ze=[{value:Ds,label:"All properties"},...re.map(G=>({value:G.id,label:G.label}))],_e=re.length>yp;function He(G){A(G),ee(G===Ds?{scope:"all"}:{scope:"group",groupKey:G})}function Te(G){O(G),ee({queryClass:G})}function Ce(G){const M=$!==G;H(M?G:null),M&&y?.(G)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(oe,{tone:"caution",children:"Includes historical data"}):null,he?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:he}):null,we?e.jsx("span",{className:"text-sm text-secondary",children:we}):null,Fe?e.jsx("span",{className:"text-sm text-secondary",children:Fe}):null,s&&f&&n?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!f?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||o,children:o?"Opening setup…":"Republish setup"}):null]})})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-b border-default pb-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-group-label",htmlFor:_e?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),_e?e.jsx("select",{id:"advanced-measurement-group",value:E,onChange:G=>He(G.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:Ze.map(G=>e.jsx("option",{value:G.value,children:G.label},G.value))}):e.jsx(Ci,{ariaLabelledBy:"advanced-measurement-group-label",value:E,options:Ze,onChange:He})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-class-label",className:"block text-sm font-medium text-heading",children:"Query type"}),e.jsx(Ci,{ariaLabelledBy:"advanced-measurement-class-label",value:C,options:vp,onChange:Te,disabled:!f})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:d,onChange:G=>j(G.target.value),placeholder:"Search properties",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]})]}),!i&&Ae?e.jsx(Rp,{values:K.shareOfVoice??[]}):null,i?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(Xe,{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??me.length," ",(t.currentView?.propertyTotal??me.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(Ip,{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:[xp.map(G=>{const M=se.startsWith(`${G.key}-`),L=M&&se.endsWith("-desc")?"descending":M?"ascending":"none";return e.jsx("th",{"aria-sort":L,className:(G.numeric,void 0),children:p?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const je=`${G.key}-${M&&se.endsWith("-asc")?"desc":"asc"}`;F(je),ee({sort:je})},"aria-label":`Sort by ${G.label.toLowerCase()}`,children:[G.label,e.jsx(Xn,{className:`h-3 w-3 transition-transform ${M?"opacity-100":"opacity-0"} ${L==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):G.label},G.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[X.map(G=>{const M=$===G.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:L=>{kp(L.target)||Ce(G.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[b?b({id:G.id,name:G.name}):G.name,Ni(G.status)||G.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[Ni(G.status)?e.jsx(oe,{tone:G.status.tone,children:G.status.label}):null,G.historical?e.jsx(oe,{tone:"caution",children:"Historical"}):null]}):null,wi(G)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:wi(G)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(jn,{metric:G.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(jn,{metric:G.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{size:"icon",variant:"ghost","aria-expanded":M,"aria-label":M?`Hide details for ${G.name}`:`Show details for ${G.name}`,onClick:()=>Ce(G.id),children:e.jsx(Xn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${M?"rotate-180":""}`,"aria-hidden":"true"})})})]},G.id),M?(G.providers??[]).map(L=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:L.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(jn,{metric:L.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(jn,{metric:L.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${G.id}:${L.provider}`)):null,M?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(Pp,{property:G,onRetryEvidence:v})})},`${G.id}:details`):null]},G.id)}),X.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),g&&t.currentView.nextCursor&&u?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",X.length," of ",t.currentView.propertyTotal]}),c?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(P,{size:"sm",variant:"outline",disabled:m,onClick:()=>u(t.currentView.nextCursor),children:m?"Loading…":c?"Retry loading more properties":"Show 50 more"})]}):g?X.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",X.length," of ",t.currentView.propertyTotal]}):null:e.jsx(cr,{shown:X.length,total:me.length,itemLabel:"properties",onShowAll:()=>q(Number.MAX_SAFE_INTEGER)})]}),!i&&!ce&&Ne>0?e.jsx("section",{"aria-label":"Flagged results",className:"border-t border-default pt-4",children:e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:["Flagged results (",Ne,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,_).map(G=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(oe,{tone:G.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:G.property}),e.jsx("span",{className:"text-secondary",children:G.summary})]},G.id))}),_<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,_).reduce((G,M)=>G+(M.count??1),0)," of ",Ne," flagged results"]}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>N(G=>Math.min(t.flaggedResults.length,G+fp)),children:"Show 50 more"})]}):ae<Ne?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ae," of ",Ne," flagged results"]}),g&&t.currentView.nextCursor&&u?e.jsx(P,{size:"sm",variant:"outline",disabled:m,onClick:()=>u(t.currentView.nextCursor),children:m?"Loading…":c?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function qo(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function $p(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 Mp({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:m,onViewChange:c,onLoadMore:h,onPropertyExpand:p,onRetryEvidence:u,renderPropertyLink:y,isRunningMeasurement:v,isOpeningSetup:b,isViewLoading:g,isLoadingMore:f,isLoadMoreError:C,viewSearch:O}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&o?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",disabled:b,onClick:o,children:b?"Opening setup…":qo(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(P,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry report"}):null]}):a?e.jsx(Tp,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:c,onLoadMore:h,onPropertyExpand:p,onRetryEvidence:u,renderPropertyLink:y,isRunningMeasurement:v,isRepublishingSetup:b,isViewLoading:g,isLoadingMore:f,isLoadMoreError:C,viewSearch:O}):e.jsx("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-secondary",children:"No advanced measurement report is available yet."})]})}const nn={numerator:null,denominator:null,reason:"plan_v1"};function Lp(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function ki(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function Dp(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function Ep(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function qp(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 Op(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Gp(t){const s=new Map;for(const n of t){const a=Op(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function Fp(t,s){if(t.plan.schemaVersion!==1)throw new Error("Version-one report adapter received a different setup version.");const n=t.plan,a=new Map(n.targets.map(b=>[b.stableKey,b])),r=new Map(n.querySnapshots.map(b=>[b.queryId,b.queryText])),o=new Map;for(const b of n.targetQuerySelections){const g=o.get(b.targetKey)??[];g.push(...b.queryIds.map(f=>r.get(f)).filter(f=>!!f)),o.set(b.targetKey,[...new Set(g)])}const i=Gp(s.evidence),m=n.executionNodes.reduce((b,g)=>b+g.expectedSnapshots,0),c=s.run?.status==="completed"&&m>0,h=c?m:0,p=c?m:0,u=s.targets.map(b=>{const g=a.get(b.id),f=i.get(b.id)??[],C=f.map(A=>({id:`${A.observationId}:${A.usageEdgeId}:${A.sourceUrl}`,kind:Dp(A.classification),query:A.queryText,url:A.sourceUrl,tone:Ep(A.classification),historical:A.historical||A.bridged})),O=f.some(A=>A.historical||A.bridged),E=s.run?b.completeness.complete?g?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${b.completeness.executed} of ${b.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:b.id,name:b.label,mentionCoverage:ki(b.mentionCoverage),citationCoverage:ki(b.citationCoverage),status:E,assignedQueries:o.get(b.id)??[],urls:g?.urls.map(Lp)??[],evidence:C,historical:O}}),y=new Map(u.map(b=>[b.id,b])),v=new Map(n.groups.map(b=>[b.stableKey,b]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:h,totalSlots:p,date:qp(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:nn,mentionCoverage:nn,citationCoverage:nn},properties:u},groups:s.groups.map(b=>({id:b.id,label:b.label,confirmedCompetitorCount:v.get(b.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:nn,mentionCoverage:nn,citationCoverage:nn},properties:b.targetIds.map(g=>y.get(g)).filter(g=>!!g)}}))},flaggedResults:[]}}const _p={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function ht(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function Up(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 Bp(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Vp({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(Xc),m=Ie({...Jc({client:V,path:{name:t},query:{period:o}}),placeholderData:Di});async function c(){n(!0),r(null);try{await ed(t,"client",o)}catch(p){const u=p instanceof dn||p instanceof Error?p.message:"Download failed";r(u)}finally{n(!1)}}if(m.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(m.error){const p=m.error instanceof Error?m.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:p})})}const h=m.data;return h?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.meta.location?` · Location: ${Bp(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",Up(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(Kp,{period:o,onChange:i}),e.jsxs(P,{variant:"secondary",size:"sm",onClick:Me(c),disabled:s,children:[e.jsx(Ji,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(Jp,{report:h}),e.jsx(ag,{report:h,audience:"client"}),e.jsx(Hp,{report:h}),e.jsx(tg,{report:h,audience:"client",projectName:t}),e.jsx(sg,{report:h})]}):null}function Kp({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Zc.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 Ai="AI Visibility — Server-Side",Pi="AI engine attention",zp=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,Qp="Live telemetry from your server logs.";function Hp({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kn,{eyebrow:Pi,title:Ai,subtitle:Qp}),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:Nu(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,o=ga(n,"requests",r),i=`${ht(s.verifiedCrawlerHits.current)} verified · ${ht(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,m=ga(s.aiUserFetchHits,"requests",r),c=ga(s.referralArrivals,"sessions",r),h=s.referralRedirects>0?`${ht(s.referralRedirects)} blocked by redirects`:"",p=[c,s.referralArrivalsClassSummary,h].filter(Boolean).join(" · "),u=s.byOperator.filter(y=>y.verifiedHits>0||y.unverifiedHits>0||y.userFetchHits>0||y.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kn,{eyebrow:Pi,title:Ai,subtitle:zp(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Fa,{label:"AI bot requests observed",value:ht(n.current),subtitle:i}),e.jsx(Fa,{label:"AI user-fetch requests",value:ht(s.aiUserFetchHits.current),subtitle:m||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Fa,{label:"AI referral sessions",value:ht(s.referralArrivals.current),subtitle:p})]}),u.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"AI tool"}),e.jsxs("th",{children:["Bot requests (",a,"d)"]}),e.jsxs("th",{children:["User fetches (",a,"d)"]}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:u.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:y.operator}),e.jsx("td",{children:ht(y.verifiedHits+y.unverifiedHits)}),e.jsx("td",{children:ht(y.userFetchHits)}),e.jsx("td",{children:ht(y.referralArrivals)})]},y.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 Wp(t,s){return t.audience==="both"||t.audience===s}const Yp={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function na(t){return Yp[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Xp(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 Jp({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,r=a>0?`${s.mentionRate}%`:"—",o=a>0?`When customers asked AI ${a} ${a===1?"query":"queries"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer queries about your business.",i=Xp(t.whatsChanged.mentionRate),m=n.providers.length>0?n.providers.map(na).join(", "):`${ht(s.queryCount)} ${s.queryCount===1?"query":"queries"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:r}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:o}),i&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${i.tone==="positive"?"text-positive-400":i.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:i.arrow}),i.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(Oa,{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(Oa,{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(Oa,{label:"AI tools tested",value:ht(s.providerCount),subtitle:m})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer queries we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"query we asked":"queries we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((c,h)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',c,'"']})]},h))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer queries where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(c=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:na(c.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(c.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[c.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",c.mentionedCount,"/",c.totalCount,")"]})]})]},c.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((c,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:c},h))})]})}function Oa({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 Zp(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function eg(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function tg({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(u=>Wp(u,s)),r=Au(t,a),o=s==="client",i=td(),[m,c]=l.useState(new Set),h=m.size>0?r.filter(u=>!u.targetRef||!m.has(u.targetRef)):r,p=u=>{if(!u.targetRef)return;const y=u.targetRef;c(v=>new Set(v).add(y)),i.mutate({projectName:n,body:{targetRef:y}},{onSuccess:()=>{Se({tone:"positive",title:`Dismissed "${u.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:v=>{Se({tone:"negative",title:`Couldn't dismiss "${u.title}"`,detail:String(v)}),c(b=>{const g=new Set(b);return g.delete(y),g})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kn,{eyebrow:o?"Action plan":"Agency actions",title:o?"What to do next":"Agency Action Plan",subtitle:o?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),h.length===0?e.jsx(mr,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:h.map((u,y)=>{const v=u.evidence.length>0?u.evidence:u.why,b=u.why.length>0||u.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:"Priority — 1 will move the needle fastest",children: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(oe,{tone:nd(u),children:o?Zp(u.horizon):sd(u.horizon)}),!o&&e.jsx(oe,{tone:"neutral",children:ad(u.category)}),e.jsx(oe,{tone:"neutral",children:o?eg(u.confidence):`${rd(u.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:u.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:u.action}),e.jsx(rg,{items:v,limit:3,className:"mt-3"}),b&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:o?"See the data behind this":"Evidence details"}),u.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:u.why.map((g,f)=>e.jsx("li",{children:g},f))})]}),u.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:u.evidence.map((g,f)=>e.jsx("li",{children:g},f))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:o?"What success looks like:":"Win condition:"})," ",u.successMetric]}),u.targetRef&&!J()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>p(u),className:"rounded-md border border-default bg-bg-elevated/50 px-2.5 py-1 text-[11px] font-medium text-neutral hover:border-mono-600 hover:bg-mono-800/70 hover:text-heading",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${u.priority}-${u.title}`)})})]})}function Ri({label:t,value:s,displayValue:n,max:a,barClass:r}){const o=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${o}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function sg({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=Pu(t).slice(0,5),o=s.length>0?Math.max(...s.map(c=>c.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(c=>c.impressions),1):0,m=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kn,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),m?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer queries about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(c=>e.jsx(Ri,{label:c.domain+(c.isCompetitor?" (competitor)":""),value:c.count,displayValue:`${ht(c.count)}×`,max:o,barClass:"bg-mono-400/70"},c.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[ht(a.indexed)," of ",ht(a.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a.indexedPct>=90?"bg-positive-500/70":a.indexedPct>=70?"bg-caution-500/70":"bg-negative-500/70"}`,style:{width:`${Math.max(a.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-medium text-strong",children:ht(a.notIndexed)})," ",a.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-strong",children:ht(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:ht(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(c=>e.jsx(Ri,{label:c.query,value:c.impressions,displayValue:`${ht(c.impressions)} ${c.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},c.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer queries where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((c,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:c.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[id(c.action),c.winnabilityClass==="ceded"&&e.jsx(oe,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(mr,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function dr(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function ur(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Ga({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=dr(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:wu(s);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:ur(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Ii({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=dr(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=Su(s,n,`vs prior ${a} days`);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[ht(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:ur(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function ng({movements:t,audience:s}){const n=t.filter(r=>r.direction!=="flat");if(n.length===0)return null;const a=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:a?"How each AI tool changed":"AI engine movements"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a?"AI tool":"Engine"}),e.jsx("th",{children:a?"Was":"Prior"}),e.jsx("th",{children:a?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(r=>{const o=r.deltaAbs>0?"+":"",i=dr(r.direction),m=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?na(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:m,children:[o,r.deltaAbs.toFixed(1),"% ",ur(r.direction)]})]},r.provider)})})]})})]})}function Ti({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const r=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!r&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:r?"What changed":"Title"}),e.jsx("th",{children:r?"Customer query":"Query"}),e.jsx("th",{children:r?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(o=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(oe,{tone:_p[o.severity],children:od(o.severity)}),o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[o.title,r&&o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:o.query}),e.jsx("td",{className:"text-xs text-secondary",children:r?na(o.provider):o.provider})]},o.id))})]})})]})}function ag({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",r=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,o=e.jsx(kn,{eyebrow:a?"Since last check":"Section 2",title:a?"What's different since last check":"What's Changed",subtitle:a?void 0:n.headline});return r?e.jsxs("section",{className:"page-section-divider",children:[o,e.jsx(mr,{message:a?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[o,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Ga,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(Ga,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(Ga,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Ii,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Ii,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(ng,{movements:n.providerMovements,audience:s}),e.jsx(Ti,{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(Ti,{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 Fa({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 kn({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 rg({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),r=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((o,i)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:o},i)),r>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",r," more"]})]})}function mr({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function ig({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[m,c]=l.useState(null),[h,p]=l.useState(t.displayName),[u,y]=l.useState(t.canonicalDomain),[v,b]=l.useState(t.country),[g,f]=l.useState(t.language),[C,O]=l.useState(t.ownedDomains??[]),[E,A]=l.useState(""),[d,j]=l.useState(t.aliases??[]),[S,q]=l.useState(""),[_,N]=l.useState(null),[T,F]=l.useState(!1),[$,H]=l.useState(!1),[ve,ue]=l.useState(""),[z,ee]=l.useState(""),[re,W]=l.useState(""),[K,R]=l.useState(""),[se,ce]=l.useState(""),[me,X]=l.useState(null),[Ae,B]=l.useState(null);l.useEffect(()=>{a||(p(t.displayName),y(t.canonicalDomain),b(t.country),f(t.language),O(t.ownedDomains??[]),j(t.aliases??[]))},[t,a]);function ae(){r(!1),c(null),p(t.displayName),y(t.canonicalDomain),b(t.country),f(t.language),O(t.ownedDomains??[]),j(t.aliases??[]),A(""),q("")}function Ne(){const M=E.trim();M&&(C.includes(M)||O([...C,M]),A(""))}function Le(M){O(C.filter(L=>L!==M))}function Fe(){const M=S.trim();if(!M)return;const L=M.toLowerCase();d.some(je=>je.toLowerCase()===L)||j([...d,M]),q("")}function Pe(M){j(d.filter(L=>L!==M))}async function Qe(){if(!(!h.trim()||!u.trim()||!v.trim()||!g.trim())){i(!0),c(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:u.trim(),ownedDomains:C,aliases:d,country:v.trim(),language:g.trim()}),r(!1),Se({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(M){c(M instanceof Error?M.message:"Failed to save")}finally{i(!1)}}}async function he(){const M=ve.trim(),L=z.trim(),je=re.trim(),qe=K.trim();if(!(!M||!L||!je||!qe)){F(!0),N(null);try{const Y={label:M,city:L,region:je,country:qe};se.trim()&&(Y.timezone=se.trim()),await dd(t.name,Y),n(),ue(""),ee(""),W(""),R(""),ce(""),H(!1),Se({title:"Location added",detail:`${M} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${M}`,dedupeMode:"drop"})}catch(Y){N(Y instanceof Error?Y.message:"Failed to add location")}finally{F(!1)}}}async function we(M){F(!0),N(null);try{await cd(t.name,M),n(),Se({title:"Location removed",detail:`${M} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${M}`,dedupeMode:"drop"})}catch(L){N(L instanceof Error?L.message:"Failed to remove location")}finally{F(!1)}}async function Ze(M){F(!0),N(null);try{await ld(t.name,M),n(),Se({title:"Default location updated",detail:`${M} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(L){N(L instanceof Error?L.message:"Failed to set default location")}finally{F(!1)}}async function _e(M){X(M),B(null);try{await ud(t.name,M),Se({title:`${M.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(L){B(L instanceof Error?L.message:"Could not download tracking results.")}finally{X(null)}}const He=h!==t.displayName||u!==t.canonicalDomain||v!==t.country||g!==t.language||JSON.stringify(C)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(d)!==JSON.stringify(t.aliases??[]),Te="w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",Ce="mb-1 block text-sm font-medium text-secondary",G=ve.trim()&&z.trim()&&re.trim()&&K.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!J()&&!a&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>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:()=>c(null),children:"×"})]}),!J()&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Display name"}),e.jsx("input",{className:Te,type:"text",value:h,onChange:M=>p(M.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Canonical domain"}),e.jsx("input",{className:Te,type:"text",value:u,onChange:M=>y(M.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Country"}),e.jsx("input",{className:Te,type:"text",value:v,onChange:M=>b(M.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Language"}),e.jsx("input",{className:Te,type:"text",value:g,onChange:M=>f(M.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:C.map(M=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[M,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Le(M),"aria-label":`Remove ${M}`,children:"×"})]},M))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Te} flex-1`,type:"text",placeholder:"docs.example.com",value:E,onChange:M=>A(M.target.value),onKeyDown:M=>M.key==="Enter"&&(M.preventDefault(),Ne())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!E.trim(),onClick:Ne,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:d.map(M=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[M,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Pe(M),"aria-label":`Remove ${M}`,children:"×"})]},M))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Te} flex-1`,type:"text",placeholder:"Facebook",value:S,onChange:M=>q(M.target.value),onKeyDown:M=>M.key==="Enter"&&(M.preventDefault(),Fe())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!S.trim(),onClick:Fe,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(P,{type:"button",disabled:o||!He||!h.trim()||!u.trim(),onClick:Me(Qe),children:o?"Saving...":"Save changes"}),e.jsx(P,{type:"button",variant:"outline",disabled:o,onClick:ae,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(M=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:M},M))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(M=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:M},M))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[_&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[_,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>N(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(M=>e.jsxs("tr",{className:"border-t border-mono-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium ${M.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[M.label,M.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:M.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:M.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:M.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:M.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!J()&&M.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:T,onClick:()=>{Ze(M.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${M.label} as default location`,children:"Set default"}),!J()&&e.jsx("button",{type:"button",disabled:T,onClick:()=>{we(M.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${M.label}`,children:"Remove"})]})})]},M.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),J()?null:$?e.jsxs("div",{className:"mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Label *"}),e.jsx("input",{className:Te,type:"text",value:ve,onChange:M=>ue(M.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"City *"}),e.jsx("input",{className:Te,type:"text",value:z,onChange:M=>ee(M.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Region *"}),e.jsx("input",{className:Te,type:"text",value:re,onChange:M=>W(M.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Country *"}),e.jsx("input",{className:Te,type:"text",value:K,onChange:M=>R(M.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Timezone (optional)"}),e.jsx("input",{className:Te,type:"text",value:se,onChange:M=>ce(M.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(P,{type:"button",size:"sm",disabled:T||!G,onClick:Me(he),children:T?"Adding...":"Add location"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:T,onClick:()=>{H(!1),N(null)},children:"Cancel"})]})]}):e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>H(!0),children:"+ Add location"})]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:me!==null,onClick:Me(()=>_e("csv")),children:me==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:me!==null,onClick:Me(()=>_e("json")),children:me==="json"?"Preparing JSON...":"Download JSON"})]})]}),Ae&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:Ae})]})]})]})}function bn(t){return{...t??{}}}function og(t,s){const n=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)),a=Object.entries(s).sort(([r],[o])=>r.localeCompare(o));return n.length===a.length&&n.every(([r,o],i)=>{const m=a[i];return m?.[0]===r&&m[1]===o})}function lg({project:t,onSave:s}){const n=Ie({queryKey:["settings"],queryFn:_i,staleTime:6e4}),[a,r]=l.useState(t.providers.length===0),[o,i]=l.useState(t.providers),[m,c]=l.useState(()=>bn(t.providerModels)),[h,p]=l.useState({providers:t.providers,providerModels:bn(t.providerModels)}),[u,y]=l.useState(!1),[v,b]=l.useState(!1),[g,f]=l.useState(null),[C,O]=l.useState(null),E=l.useRef(null),A=n.data?.providerCatalog??[],d=l.useMemo(()=>new Set((n.data?.providers??[]).filter($=>$.configured).map($=>$.name)),[n.data]),j=l.useMemo(()=>{const $=new Map(A.map(H=>[H.name,H]));for(const H of Object.keys(m))$.has(H)||$.set(H,{name:H,displayName:H,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...$.values()].sort((H,ve)=>H.displayName.localeCompare(ve.displayName))},[A,m]),S=!og(m,h.providerModels);l.useEffect(()=>{if(u||v)return;const $={providers:t.providers,providerModels:bn(t.providerModels)};p($),r($.providers.length===0),i($.providers),c($.providerModels)},[t]);function q(){b(!0),r(!1),o.length===0&&i([...d])}function _($,H,ve=!1){b(!0),c(ue=>{const z={...ue};return H==="__inherit__"?delete z[$]:H==="__custom__"?z[$]=ve?"":z[$]??"":z[$]=H,z}),H==="__custom__"&&queueMicrotask(()=>E.current?.focus())}function N($,H){b(!0),i(ve=>H?[...new Set([...ve,$])]:ve.filter(ue=>ue!==$))}function T(){b(!1),r(h.providers.length===0),i(h.providers),c(bn(h.providerModels)),f(null),O(null)}async function F(){if(!(n.isError||n.isLoading||!a&&o.length===0)){y(!0),f(null),O(null);try{const $=Object.fromEntries(Object.entries(m).filter(([ve,ue])=>ue.trim()!==""&&(a||o.includes(ve)))),H={providers:a?[]:o,providerModels:$};await s(H),p({providers:[...H.providers],providerModels:bn(H.providerModels)}),b(!1),O("Engine settings saved. They apply on the next sweep.")}catch($){f(tr($))}finally{y(!1)}}}return J()?null:n.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):n.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):A.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):d.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(os,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":u,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:u,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{b(!0),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:q})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:j.map($=>{const H=o.includes($.name),ve=d.has($.name),ue=H&&!ve,z=m[$.name],ee=$.knownModels.some(W=>W.id===z),re=z===void 0?"__inherit__":ee?z:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:H,disabled:!ve&&!H,onChange:W=>N($.name,W.target.checked)})," ",e.jsx("span",{children:$.displayName}),ue&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),H&&($.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${$.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${$.name}`,value:re,onChange:W=>_($.name,W.target.value,ee),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",$.defaultModel||"default"]}),$.knownModels.map(W=>e.jsx("option",{value:W.id,children:W.displayName},W.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),re==="__custom__"&&e.jsx("input",{ref:E,"aria-label":`${$.displayName} custom model ID`,value:z??"",onChange:W=>{b(!0),c(K=>({...K,[$.name]:W.target.value}))},"aria-describedby":`project-model-hint-${$.name}`}),e.jsxs("p",{id:`project-model-hint-${$.name}`,className:"project-engine-help",children:[z?"Project override":"Inherited from instance settings",". ",$.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},$.name)})})]}),!a&&o.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),g&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:g}),C&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:C}),S&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{type:"button",onClick:()=>{F()},disabled:u||!a&&o.length===0,children:u?"Saving engines…":"Save engines"}),e.jsx(P,{type:"button",variant:"outline",onClick:T,disabled:u,children:"Cancel"})]})]})}const cg=[{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"}],$i=["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 dg({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState("daily"),[m,c]=l.useState(6),[h,p]=l.useState(""),[u,y]=l.useState("UTC"),[v,b]=l.useState(!1),[g,f]=l.useState(""),[C,O]=l.useState(!1),[E,A]=l.useState(!1),[d,j]=l.useState(null);l.useEffect(()=>{md(t).then(n).catch(()=>n(null))},[t]);const S=()=>{if(s&&s!=="loading"){const T=xd(s.preset??null,s.cronExpr);i(T.freq),c(T.hour),p(T.customCron);const F=$i.includes(s.timezone);y(F?s.timezone:"Other"),b(!F),f(F?"":s.timezone)}else i("daily"),c(6),p(""),y("UTC"),b(!1),f("");j(null),r(!0)},q=async()=>{O(!0),j(null);try{const F={timezone:v?g.trim()||"UTC":u};o==="custom"?F.cron=h.trim():F.preset=gd(o,m);const $=await kr(t,F);n($),r(!1),Se({title:"Schedule saved",detail:xa($.preset??null,$.cronExpr,$.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(T){j(T instanceof Error?T.message:"Failed to save schedule")}finally{O(!1)}},_=async()=>{if(!(!s||s==="loading")){O(!0),j(null);try{const T={timezone:s.timezone,enabled:!s.enabled};s.preset?T.preset=s.preset:T.cron=s.cronExpr;const F=await kr(t,T);n(F),Se({title:F.enabled?"Schedule resumed":"Schedule paused",detail:xa(F.preset??null,F.cronExpr,F.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(T){j(T instanceof Error?T.message:"Failed to update schedule")}finally{O(!1)}}},N=async()=>{A(!0),j(null);try{await pd(t),n(null),r(!1),Se({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(T){j(T instanceof Error?T.message:"Failed to remove schedule")}finally{A(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),!J()&&s!=="loading"&&!a&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:S,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===null&&e.jsx(de,{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(de,{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:xa(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(oe,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!J()&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:C,onClick:Me(_),children:s.enabled?"Pause":"Resume"}),!J()&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:E,onClick:Me(N),children:E?"Removing...":"Remove"})]})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:d})]}),!J()&&a&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:o,onChange:T=>i(T.target.value),children:cg.map(T=>e.jsx("option",{value:T.value,children:T.label},T.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:m,disabled:o==="twice-daily"||o==="custom",onChange:T=>c(parseInt(T.target.value)),children:Array.from({length:24},(T,F)=>e.jsx("option",{value:F,children:hd(F)},F))})]})]}),o==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:h,onChange:T=>p(T.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:v?"Other":u,onChange:T=>{T.target.value==="Other"?(b(!0),y("Other")):(b(!1),y(T.target.value))},children:[$i.map(T=>e.jsx("option",{value:T,children:T},T)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),v&&e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:g,onChange:T=>f(T.target.value)})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),j(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:C||o==="custom"&&!h.trim(),onClick:Me(q),children:C?"Saving...":"Save schedule"})]})]})]})}const ug=[{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 mg({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[m,c]=l.useState(["citation.lost","citation.gained"]),[h,p]=l.useState(!1),[u,y]=l.useState(null),[v,b]=l.useState({}),[g,f]=l.useState(new Set);l.useEffect(()=>{fd(t).then(n).catch(()=>n([]))},[t]);const C=d=>{c(j=>j.includes(d)?j.filter(S=>S!==d):[...j,d])},O=async()=>{if(!(!o.trim()||m.length===0)){p(!0),y(null);try{const d=await bd(t,{channel:"webhook",url:o.trim(),events:m});n(j=>j==="loading"?[d]:[...j,d]),i(""),c(["citation.lost","citation.gained"]),r(!1),Se({title:"Webhook added",detail:`Notifications will be sent to ${d.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(d){y(d instanceof Error?d.message:"Failed to add webhook")}finally{p(!1)}}},E=async d=>{if(!g.has(d)){f(j=>new Set(j).add(d));try{await vd(t,d),n(j=>j==="loading"?j:j.filter(S=>S.id!==d)),Se({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${d}`,dedupeMode:"drop"})}catch(j){y(j instanceof Error?j.message:"Failed to remove webhook")}finally{f(j=>{const S=new Set(j);return S.delete(d),S})}}},A=async d=>{b(j=>({...j,[d]:{state:"testing"}}));try{const j=await yd(t,d);b(S=>({...S,[d]:{state:j.ok?"ok":"fail",status:j.status}})),j.ok&&Se({title:"Test notification sent",detail:`Webhook returned status ${j.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${d}`,dedupeMode:"replace"})}catch{b(j=>({...j,[d]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),!J()&&s!=="loading"&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),y(null)},children:a?"Cancel":"+ Add webhook"})]}),!J()&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:o,onChange:d=>i(d.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:ug.map(d=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:m.includes(d.value),onChange:()=>C(d.value)}),e.jsx("span",{className:"text-sm text-neutral",children:d.label})]},d.value))})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm",children:u}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),y(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:h||!o.trim()||m.length===0,onClick:Me(O),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(de,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:d.urlHost,children:d.urlDisplay??d.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:d.events.map(j=>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:j.replace("."," ")},j))})}),e.jsx("td",{children:e.jsx(oe,{tone:d.enabled?"positive":"neutral",children:d.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[v[d.id]&&(()=>{const j=v[d.id],S=j.state==="testing"?"Sending…":j.state==="ok"?`Delivered${j.status?` (${j.status})`:""}`:`Failed${j.status?` (${j.status})`:""}`;return e.jsx(oe,{tone:j.state==="ok"?"positive":j.state==="fail"?"negative":"neutral",children:S})})(),!J()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:v[d.id]?.state==="testing",onClick:()=>{A(d.id)},children:"Test"}),!J()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:g.has(d.id),onClick:()=>{E(d.id)},children:g.has(d.id)?"Removing…":"Remove"})]})})]},d.id))})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:u})]})]})}const Mi=2e3,Li=3e5;function hg(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 xg({projectName:t,refreshNonce:s}){const n=Rs(),[a,r]=l.useState(null),[o,i]=l.useState([]),[m,c]=l.useState(null),[h,p]=l.useState([]),[u,y]=l.useState([]),[v,b]=l.useState(null),[g,f]=l.useState(""),[C,O]=l.useState(""),[E,A]=l.useState(""),[d,j]=l.useState(!0),[S,q]=l.useState(!1),[_,N]=l.useState(null),[T,F]=l.useState("performance");l.useEffect(()=>{$()},[t,s]);async function $(){j(!0),N(null);try{const R=await n.fetchQuery({...Wi({client:V,path:{name:t}}),staleTime:Tt});if(r(R),R.connected){const[se,ce,me,X]=await Promise.all([n.fetchQuery({...Vd({client:V,path:{name:t}}),staleTime:Tt}).catch(()=>null),n.fetchQuery({...Kd({client:V,path:{name:t}}),staleTime:Tt}).catch(()=>[]),n.fetchQuery({...zd({client:V,path:{name:t}}),staleTime:Tt}).catch(()=>[]),R.siteUrl?Promise.resolve([]):n.fetchQuery({...Qd({client:V,path:{name:t}}),staleTime:Tt}).then(Ae=>Ae.sites).catch(()=>[])]);c(se),p(ce),y(me),i(X)}else c(null),p([]),y([]),i([])}catch(R){N(R instanceof Error?R.message:"Failed to load Bing data")}finally{j(!1)}}async function H(){if(C.trim()){N(null);try{const R=await Hd(t,C.trim());await ft(n,"bing"),O(""),R.availableSites.length>0&&i(R.availableSites),await $()}catch(R){N(R instanceof Error?R.message:"Failed to connect")}}}async function ve(){try{await Wd(t),await ft(n,"bing"),r(null),i([]),c(null),p([]),y([]),b(null),A(""),N(null)}catch(R){N(R instanceof Error?R.message:"Failed to disconnect")}}async function ue(){if(E)try{await Yd(t,E),await ft(n,"bing"),await $()}catch(R){N(R instanceof Error?R.message:"Failed to set site")}}async function z(){if(g.trim())try{const R=await Xd(t,g.trim());await ft(n,"bing"),b(R),p(se=>[R,...se])}catch(R){N(R instanceof Error?R.message:"Inspection failed")}}async function ee(R){q(!0),N(null);try{const se=await Pr(t,{urls:[R]}),{succeeded:ce,failed:me,total:X}=se.summary;Se({title:"Bing submission requested",detail:me===0?`${ce} URL submitted to Bing.`:`${ce}/${X} submitted successfully, ${me} failed.`,tone:me===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${R}`,dedupeMode:"replace"})}catch(se){const ce=se instanceof Error?se.message:"Submission failed";N(ce),Se({title:"Bing submission failed",detail:ce,tone:"negative",dedupeKey:`bing:indexing:${t}:${R}`,dedupeMode:"replace"})}finally{q(!1)}}async function re(){q(!0),N(null),Se({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const R=await Pr(t,{allUnindexed:!0}),{succeeded:se,failed:ce,total:me}=R.summary;Se({title:"Bing submissions requested",detail:ce===0?`${se}/${me} URL${me!==1?"s":""} submitted to Bing.`:`${se}/${me} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(R){const se=R instanceof Error?R.message:"Batch submission failed";N(se),Se({title:"Bing submissions failed",detail:se,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{q(!1)}}if(d)return e.jsx(de,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return J()?e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:C,onChange:R=>O(R.target.value),onKeyDown:R=>{R.key==="Enter"&&H()}}),e.jsx(Ye,{size:"sm",disabled:!C.trim(),onClick:Me(H),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),_&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:_})]});if(!a.siteUrl)return e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Me(ve),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"}),o.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:E,onChange:R=>A(R.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map(R=>e.jsxs("option",{value:R.url,children:[R.url,R.verified?" (verified)":""]},R.url))]}),!J()&&e.jsx(Ye,{size:"sm",disabled:!E,onClick:Me(ue),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),_&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:_})]});const W=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],K=W.find(R=>R.key===T)??W[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(de,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Me(ve),children:"Disconnect"})]})]}),_&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:_}),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(de,{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:K.eyebrow}),e.jsx("h3",{children:K.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:W.map(R=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${T===R.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>F(R.key),children:R.label},R.key))}),T==="coverage"&&m&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx($n,{label:"Indexed",value:m.summary.indexed,tone:"positive"}),e.jsx($n,{label:"Not in index",value:m.summary.notIndexed+(m.summary.unknown??0),tone:"negative"}),e.jsx($n,{label:"Status unknown",value:m.summary.unknown??0,tone:"neutral"}),e.jsx($n,{label:"Coverage",value:`${m.summary.percentage}%`,tone:"neutral"})]}),m.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",m.notIndexed.length,")"]}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:S,onClick:Me(re),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!J()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:m.notIndexed.map(R=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:R.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.httpCode??"—"}),!J()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{ee(R.url)},children:"Submit"})})]},R.id))})]})})]}),(m.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(m.unknown??[]).length,")"]}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:S,onClick:Me(re),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!J()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(m.unknown??[]).map(R=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:R.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.lastCrawledDate?Ot(R.lastCrawledDate):"—"}),!J()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{ee(R.url)},children:"Submit"})})]},R.id))})]})})]}),m.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",m.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:m.indexed.map(R=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:R.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.lastCrawledDate?Ot(R.lastCrawledDate):"—"})]},R.id))})]})})]})]}),T==="coverage"&&!m&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),T==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!J()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:g,onChange:R=>f(R.target.value),onKeyDown:R=>{R.key==="Enter"&&z()}}),e.jsx(Ye,{size:"sm",disabled:!g.trim(),onClick:Me(z),children:"Inspect"})]}),v&&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:v.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:v.inIndex?"text-positive-400":"text-negative-400",children:v.inIndex?"Yes":"No"})," · ","HTTP: ",v.httpCode??"—"," · ","Crawled: ",v.lastCrawledDate??"—"]})]}),h.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:h.map(R=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:R.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(oe,{tone:R.inIndex?"positive":"negative",children:R.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Ot(R.inspectedAt)})]},R.id))})]})})]}),T==="performance"&&e.jsx("div",{className:"mt-4",children:u.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Tn[Fs.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Tn[Fs.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Tn[Fs.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Tn[Fs.Position]})]})}),e.jsx("tbody",{children:u.map((R,se)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:R.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:R.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:R.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(R.ctr)?R.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:R.averagePosition.toFixed(1)})]},se))})]})})})]})]})}function pg({projectName:t}){const s=Rs(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,m]=l.useState("idle"),[c,h]=l.useState(null),p=l.useRef(null),[u,y]=l.useState(null),[v,b]=l.useState(null),[g,f]=l.useState(0);async function C(E=!1){E||o(!0),h(null);try{const[A,d]=await Promise.all([s.fetchQuery({...er({client:V,path:{name:t}}),staleTime:Tt}).catch(()=>[]),s.fetchQuery({...Wi({client:V,path:{name:t}}),staleTime:Tt}).catch(()=>null)]),j=A.find(S=>S.connectionType==="gsc")??null;y(j),b(d)}catch(A){h(A instanceof Error?A.message:"Failed to load search engine connections")}finally{o(!1)}}async function O(){if(i!=="idle")return;p.current?.abort();const E=new AbortController;p.current=E;const A=E.signal;m("syncing"),h(null),Se({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const d=[],j=[];try{async function S(){if(!u)return;const N=await Ud(t);if(!N?.id)return;const T=Date.now()+Li;for(;Date.now()<T;){if(A.aborted||(await new Promise($=>setTimeout($,Mi)),A.aborted))return;const F=await Ua(N.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled"].includes(F.status)){F.status!=="completed"&&d.push(`Google sync ${F.status}`);return}}j.push("Google sync is still running — search data will appear shortly")}async function q(){if(!v?.connected)return;const N=await Bd(t).catch(()=>null);if(!N?.id){d.push("Bing sweep could not be started");return}const T=Date.now()+Li;for(;Date.now()<T;){if(A.aborted||(await new Promise($=>setTimeout($,Mi)),A.aborted))return;const F=await Ua(N.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled","partial"].includes(F.status)){F.status==="failed"?d.push("Bing sweep failed"):F.status==="partial"&&j.push("Bing sweep finished with some pages unverified");return}}j.push("Bing sweep is still running — coverage will update shortly")}const _=await Promise.allSettled([S(),q()]);for(const N of _)N.status==="rejected"&&d.push(N.reason instanceof Error?N.reason.message:"Sync failed");if(await Promise.all([ft(s,"gsc"),ft(s,"bing")]),A.aborted)return;if(m("reloading"),await C(!0),f(N=>N+1),d.length>0){const N=`Partial refresh: ${[...d,...j].join("; ")}`;h(N),Se({title:"Search coverage partially refreshed",detail:N,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else j.length>0?Se({title:"Search coverage refresh incomplete",detail:j.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Se({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(S){if(!A.aborted){const q=S instanceof Error?S.message:"Refresh failed";h(q),Se({title:"Search coverage refresh failed",detail:q,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{A.aborted||m("idle")}}return l.useEffect(()=>(C(),()=>{p.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([E,A])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===E,className:`project-subnav-link ${n===E?"project-subnav-link-active":""}`,onClick:()=>a(E),children:A},E))}),!J()&&e.jsxs(Ye,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{O()},children:[e.jsx(Wn,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),c&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:c}),n==="google"&&e.jsx(Nm,{projectName:t,refreshNonce:g}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(xg,{projectName:t,refreshNonce:g})]})]})}function aa({label:t,summary:s,displayValue:n,tooltip:a}){const r=s.value.trim()!==""&&Number.isFinite(Number(s.value)),o=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Xe,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${Ei[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,r?e.jsx("span",{className:"text-faint",children:"%"}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${o}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function gg({model:t,sweepRunning:s}){const n=t.citationMovement,a=t.mentionMovement,r=t.movementComparison,o=t.recentRuns.find(y=>y.kind===Ks["answer-visibility"]),i=y=>y.tone==="positive"?"improved":y.tone==="negative"?"declined":y.gained>0||y.lost>0?"mixed":"steady",m=i(a),c=i(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===c)return m==="steady"?"Answer mentions and citation coverage held steady":m==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${m}`;const y=m==="mixed"?"Answer mention movement was mixed":m==="steady"?"Answer mentions held steady":`Answer mentions ${m}`,v=c==="mixed"?"citation movement was mixed":c==="steady"?"citation coverage held steady":`citation coverage ${c}`;return`${y}; ${v}`})(),p=[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(", "),u=`${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(Xe,{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:o?`Updated ${o.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(aa,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(aa,{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?`${p||"Query set changed"} · ${u}.`:`${u}.`})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No comparison yet"}),e.jsx("p",{className:"overview-brief-panel-copy",children:"Run another sweep to measure mention and citation movement."})]})]})]})]})}function _a({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:o}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:r||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(Xn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function fg({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=qi(),r=Hi(),[o,i]=l.useState(new Set);if(t.length===0&&s.rows.length===0)return null;const m=f=>{i(C=>{const O=new Set(C);return O.delete(f),O})},c=f=>{i(C=>new Set(C).add(f)),r.mutate({projectName:n,queries:[f]},{onSuccess:()=>{Se({tone:"positive",title:`Tracking "${f}"`}),m(f)},onError:C=>{Se({tone:"negative",title:`Could not track "${f}"`,detail:String(C)}),m(f)}})},h=f=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:f.title}),f.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:f.detail}):null]}),e.jsx(oe,{tone:f.tone,children:f.actionLabel})]}),f.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",f.affectedPhrases.length," affected ",f.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:f.affectedPhrases.map((C,O)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(Va,{state:C.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:C.query}),C.provider?e.jsx(cn,{provider:C.provider}):null,!J()&&C.evidenceId?e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(C.evidenceId)},children:"View evidence"}):null]},C.evidenceId||`${f.id}-${O}`))})]}):null]},f.id),p=f=>{const C=o.has(f.query);return e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:f.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:f.reason})]}),J()?null:e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:C,"aria-label":`Track query "${f.query}"`,onClick:()=>c(f.query),children:C?"Tracking…":"Track"})]},f.query)},u=t.slice(0,1),y=s.rows.slice(0,1),v=t.slice(1),b=s.rows.slice(1),g=v.length+b.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[u.map(h),y.map(p)]}),g>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[g," more ",g===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[v.map(h),b.map(p)]})]}):null]})}function Mg(t){const{projectName:s}=Ho({from:"/projects/$projectName"}),a=jd()?.dashboard.projects.find(y=>y.project.name===s||y.project.id===s)?.project.name??null,r=Ie({...Nd({client:V}),enabled:!a}),o=a??r.data?.find(y=>y.name===s||y.id===s)?.name??null,{commandCenter:i,isLoading:m,latestVisibilityRevision:c,refetch:h}=wd(o),p=!a&&r.isLoading||m;return!o&&!a&&r.isSuccess&&!m?e.jsx("div",{className:"page-container",children:e.jsxs(de,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(P,{asChild:!0,children:e.jsx(os,{to:"/",children:"Return to overview"})})]})}):!i||p?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(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(yg,{model:i,refetch:h,latestVisibilityRevision:c,...t})}function bg({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const i=c=>{r.current&&!r.current.contains(c.target)&&a(!1)},m=c=>{c.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",i),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",m)}},[n]),t.length===0)return null;const o=t.some(i=>i.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${o?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(i=>!i),children:["More",e.jsx(Xn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(i=>e.jsx(os,{to:i.href,role:"menuitem",className:`project-subnav-menu-item ${i.key===s?"project-subnav-menu-item-active":""}`,"aria-current":i.key===s?"page":void 0,onClick:()=>a(!1),children:i.label},i.key))}):null]})}function yg({tab:t,model:s,refetch:n,latestVisibilityRevision:a}){const r=Wo(),o=Rs(),{canWrite:i}=Qi(),m=l.useMemo(()=>{const k=Sd();return k?Cd(k.projectTabs):void 0},[]),c=kd(t,m),h=l.useMemo(()=>s.competitors.map(k=>k.domain),[s.competitors]),[p,u]=l.useState(!1),[y,v]=l.useState(!1),b=Hi(),g=Yo({strict:!1}),f=g.manageQueries===!0,C=l.useCallback(()=>{r({to:".",replace:!0,search:k=>({...k,siteHealthRunId:void 0})})},[r]),[O,E]=l.useState(f),[A,d]=l.useState(""),[j,S]=l.useState(!1),[q,_]=l.useState(null),[N,T]=l.useState(!1),[F,$]=l.useState(""),[H,ve]=l.useState(!1),[ue,z]=l.useState(void 0),[ee,re]=l.useState(!1),[W,K]=l.useState(null),[R,se]=l.useState(null),[ce,me]=l.useState(!1),X=Mu(g),[Ae,B]=l.useState(void 0),[ae,Ne]=l.useState(void 0),Le=l.useCallback(k=>{B(k.search),k.sort&&Ne(k.sort),r({to:".",search:be=>({...be,...Du(k)}),replace:!1})},[r]),[Fe,Pe]=l.useState(!1),Qe=s?.visibilityEvidence??[],he=s?.project.name??"",we=s?.project.displayName||s?.project.name||he,Ze=Ad(),_e=Ie({...Pd({client:V,path:{name:he}}),enabled:c==="portfolio"&&!!he,staleTime:0,refetchOnMount:"always"}),He=Ie({...Rd({client:V,path:{name:he}}),enabled:!J()&&!!he,retry:!1}),Te=Ie({...Id({client:V,path:{name:he}}),enabled:!J()&&(c==="portfolio"||c==="overview"||c==="settings")&&!!he,staleTime:0,refetchOnMount:"always"}),Ce=Ie({...Td({client:V,path:{name:he}}),enabled:!J()&&(c==="portfolio"||c==="overview"||c==="settings")&&!!he,staleTime:0,refetchOnMount:"always"}),G=He.data,M=G?.enabled&&G.nextRunAt?`Next AI sweep ${new Date(G.nextRunAt).toLocaleString()}`:null,L=Te.data?.active??null,je=Te.data!==void 0,qe=new Set(L&&Number(L.plan.schemaVersion)===2?L.plan.groups?.map(k=>k.stableKey)??[]:[]),Be={...X.scope==="group"&&!!X.groupKey&&je&&!qe.has(X.groupKey)?{scope:"all",queryClass:X.queryClass}:X,...Ae?{search:Ae}:{}},mt=L===null?null:Number(L.plan.schemaVersion),ot=L?.revision??0,De=je?`${he}:${ot}`:null,Oe=l.useRef(null);l.useEffect(()=>{const k=Oe.current;De!==null&&(Oe.current=De),Lu(k,De)&&(Le({scope:"all",queryClass:"all"}),Pe(!1))},[De,Le]);const xt={client:V,path:{name:he},query:{scope:Be.scope,...Be.groupKey?{groupKey:Be.groupKey}:{},queryClass:Be.queryClass,...Be.search?{search:Be.search}:{},...ae?{sort:ae}:{},limit:50}},We=Xo({...$d(xt),enabled:c==="overview"&&!!he&&mt===2,initialPageParam:xt,getNextPageParam:(k,be)=>{if(!k.properties.nextCursor)return;const ye=be[0]?.measurement.displayedRunId;return{path:xt.path,query:{...xt.query,cursor:k.properties.nextCursor,...ye?{runId:ye}:{}}}},placeholderData:Di,staleTime:0,refetchOnMount:"always"}),Ve=We.data?.pages[0]?.measurement.displayedRunId,$e=Ie({...Md({client:V,path:{name:he},query:{revision:ot,...Ve?{runId:Ve}:{}}}),enabled:c==="overview"&&!!he&&L!==null&&(mt===1||Fe&&Ve!==void 0),staleTime:0,refetchOnMount:"always"}),jt=Te.data!==void 0,Mt=_e.data!==void 0,Ue=Te.isPending&&!jt,Ge=Te.isError&&!jt,bt=_e.isPending&&!Mt,Ke=_e.isError&&!Mt,Nt=$e.data!==void 0,kt=$p({activePlanSchemaVersion:Ce.data?.activeSchemaVersion??mt,hasDraft:Ce.data?.draft!==null&&Ce.data?.draft!==void 0}),yt=Ce.data===void 0&&Te.data===void 0&&(Te.isLoading||Ce.isLoading),At=Ce.data!==void 0?"success":Ce.isError?"error":"pending",lt=l.useMemo(()=>{const k=We.data?.pages;return k?!fu(k):!1},[We.data]),U=l.useMemo(()=>{const k=We.data?.pages,be=k?.[0],ye=k?.at(-1);if(!(!be||!ye||lt))return{...be,properties:{...be.properties,items:k.flatMap(I=>I.properties.items),nextCursor:ye.properties.nextCursor}}},[lt,We.data]),ke=l.useMemo(()=>{if(L)return L.plan.schemaVersion===1?$e.data?Fp(L,$e.data):void 0:U?bu({overview:U,activePlan:L,sort:ae,report:$e.data,reportState:U.measurement.displayedRunId===void 0?"ready":$e.isFetching&&$e.data===void 0?"loading":$e.isError&&$e.data===void 0?"error":$e.data?"ready":"loading"}):void 0},[L,$e.data,$e.isError,$e.isFetching,U]),fe=mt===2?lt?"error":We.isPending?"loading":We.isError&&ke===void 0?"error":"ready":$e.isPending&&!Nt?"loading":$e.isError&&!Nt?"error":"ready",pe=(s?.recentRuns??[]).some(k=>k.kind===Ks["answer-visibility"]&&(k.status===Ar.running||k.status===Ar.queued)),Lt=l.useMemo(()=>(s?.project.locations??[]).map(k=>k.label),[s?.project.locations]),ct=l.useMemo(()=>new Set(Qe.map(k=>k.location??"")),[Qe]),Pt=ct.has(""),Dt=l.useMemo(()=>[...new Set(Qe.map(k=>k.query))].sort((k,be)=>k.localeCompare(be)),[Qe]),Jt=l.useMemo(()=>{const k=[...ct].filter(Boolean);return k.length>1?k:Lt},[ct,Lt]);l.useEffect(()=>{if(ue===void 0||ue===""||!he){se(null),me(!1);return}me(!0),Ld(he,ue,20).then(k=>{se(k),me(!1)}).catch(()=>{se(null),me(!1)})},[ue,he]);const Et=l.useMemo(()=>{if(!R)return null;const k=new Map;for(const be of R){for(const[ye,I]of Object.entries(be.providerRuns??{}))k.set(`${be.query}::${ye}`,I.map(Q=>({runId:Q.runId,citationState:Q.citationState,createdAt:Q.createdAt,answerMentioned:Q.answerMentioned,visibilityState:Q.visibilityState,visibilityTransition:Q.visibilityTransition,mentionState:Q.mentionState,mentionTransition:Q.mentionTransition})));(!be.providerRuns||Object.keys(be.providerRuns).length===0)&&k.set(`${be.query}::`,be.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 k},[R]),ls=l.useMemo(()=>{let k=ue!==void 0?Qe.filter(be=>ue===""?!be.location:be.location===ue):Qe;if(W){const be=W.toLowerCase();k=k.filter(ye=>ye.competitorDomains.some(I=>I.toLowerCase()===be))}return Et?k.map(be=>{const ye=Et.get(`${be.query}::${be.provider}`)??Et.get(`${be.query}::`);return ye?{...be,runHistory:ye}:be}):k},[Qe,ue,W,Et]);async function at(){try{await Ze.mutateAsync({projectName:he,projectLabel:we,sourceAction:"project-run"}),n()}catch{}}async function ps(){v(!0);try{await _d(he),Se({title:"Project deleted",detail:`${we} was removed.`,tone:"positive",dedupeKey:`project:delete:${he}`,dedupeMode:"drop"}),r({to:"/"}),n()}catch(k){console.error("Failed to delete project:",k)}finally{v(!1)}}async function wt(){const k=A.split(`
|
|
8
|
+
`).map(be=>be.trim()).filter(Boolean);if(k.length!==0){S(!0);try{await Od(he,k),n(),d("")}finally{S(!1)}}}async function gs(k){_(k);try{await qd(he,[k]),n()}catch(be){Se({title:"Could not remove query",detail:be instanceof Error?be.message:`Failed to remove "${k}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{_(null)}}async function Ft(){const k=F.trim();if(k){ve(!0);try{await Dd(he,[k]),n(),$(""),T(!1)}finally{ve(!1)}}}async function Zt(k){const be=s.competitors.find(ye=>ye.domain===k);if(!be){Se({title:"Could not remove competitor",detail:`Could not find ${k} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await Ed(he,be.id),n()}catch(ye){Se({title:"Could not remove competitor",detail:ye instanceof Error?ye.message:`Failed to remove ${be.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function Vt(k,be){const ye=await Gd(k,be);return await o.invalidateQueries({queryKey:zi({client:V})}),o.setQueryData(Fd({client:V,path:{name:k}}),ye),hg(o,ye),ye}const et=`/projects/${encodeURIComponent(s.project.name)}`,fs=[{key:"overview",label:"AI Visibility",href:et},{key:"search-console",label:"Search Engines",href:`${et}/search-console`},{key:"activity",label:"Activity",href:`${et}/activity`},{key:"technical-aeo",label:"Site Health",href:`${et}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${et}/conversions`},{key:"local",label:"Local Presence",href:`${et}/local`},{key:"discovery",label:"Query Discovery",href:`${et}/discovery`},{key:"backlinks",label:"Backlinks",href:`${et}/backlinks`}],_t=[{key:"report",label:"Report",href:`${et}/report`},{key:"history",label:"Change History",href:`${et}/history`}],St=fs.filter(k=>pa(k.key,m)),bs=_t.filter(k=>pa(k.key,m)),dt=pa("settings",m)?{key:"settings",label:"Settings",href:`${et}/settings`}:null;function ns(k,be=!1){const ye=document.getElementById(k);if(!ye)return;be&&ye instanceof HTMLDetailsElement&&(ye.open=!0);const I=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{ye.scrollIntoView({behavior:I?"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]}),!J()&&e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map(k=>e.jsx("span",{className:"tag",children:k},k))]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!J()&&e.jsxs("div",{className:"flex items-center gap-3",children:[M?e.jsx("p",{className:"text-sm text-secondary",children:M}):null,e.jsx(Ye,{type:"button",variant:"outline",disabled:Ze.isPending||pe,onClick:Me(at),children:Ze.isPending?"Starting…":pe?"AI sweep running…":"Run AI sweep"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[St.map(k=>e.jsx(os,{to:k.href,className:`project-subnav-link ${k.key===c?"project-subnav-link-active":""}`,"aria-current":k.key===c?"page":void 0,children:k.label},k.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(bg,{items:bs,activeTab:c}),dt&&e.jsx(os,{to:dt.href,className:`project-subnav-link ${c==="settings"?"project-subnav-link-active":""}`,"aria-current":c==="settings"?"page":void 0,children:dt.label},dt.key)]})]}),c==="portfolio"&&!J()?e.jsx(hp,{projectName:he,canEdit:i,queries:_e.data??[],isQueryLoading:bt,isQueryError:Ke,onRetryQueries:()=>{_e.refetch()},publishedPlan:L,onCreateQueries:async k=>(await b.mutateAsync({projectName:he,queries:[...k]}),(await _e.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{r({to:"/projects/$projectName",params:{projectName:he},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([Ce.refetch(),Te.refetch()]).finally(()=>{r({to:"/projects/$projectName",params:{projectName:he}})})}},he):c==="overview"?yt?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):e.jsxs(e.Fragment,{children:[Ge?e.jsxs("div",{role:"alert",className:"mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("span",{children:"Could not check the advanced measurement setup. Existing project-wide results remain available."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{Te.refetch()},children:"Retry setup check"})]}):null,e.jsx(Mp,{mode:kt,canEdit:i&&!J()&&!Ue&&!Ge,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Ih,{projectName:s.project.name,competitorDomains:h,analyticsRevision:a})}),e.jsx(gg,{model:s,sweepRunning:pe}),e.jsx(fg,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:s.project.name}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),!J()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>T(!N),children:N?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(Fu,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:h},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(aa,{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(aa,{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."})]})})]}),N&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"competitor.com",value:F,onChange:k=>$(k.target.value),onKeyDown:k=>{k.key==="Enter"&&Ft()}}),e.jsx(Ye,{type:"button",size:"sm",disabled:!F.trim()||H,onClick:Me(Ft),children:H?"Adding...":"Add"})]}),s.competitors.length>0&&e.jsxs("details",{className:"inline-disclosure mt-4",children:[e.jsx("summary",{children:"Review tracked competitors"}),e.jsx("div",{className:"mt-3",children:e.jsx(Yu,{competitors:s.competitors,onSelectCompetitor:k=>{K(k),ns("evidence-section",!0)},onRemoveCompetitor:J()?void 0:k=>{Zt(k)},activeFilter:W})})]})]}),e.jsxs(_a,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:J(),children:[!J()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>E(!O),children:O?"Done":"Manage queries"})}),!J()&&O&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Dt.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:Dt.map(k=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:k,children:k}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50","aria-label":`Remove query ${k}`,title:`Stop tracking "${k}"`,disabled:q!==null,onClick:()=>{gs(k)},children:q===k?"Removing…":"Remove"})]},k))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:A,onChange:k=>d(k.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[A.split(`
|
|
9
|
+
`).filter(k=>k.trim()).length," to add"]}),e.jsx(Ye,{type:"button",size:"sm",disabled:!A.trim()||j,onClick:Me(wt),children:j?"Adding...":"Add queries"})]})]}),s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${ue===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":ue===void 0,onClick:()=>{z(void 0)},children:"All locations"}),s.project.locations.map(k=>e.jsx("button",{className:`filter-chip ${ue===k.label?"filter-chip-active":""}`,type:"button","aria-pressed":ue===k.label,onClick:()=>{z(k.label),re(!1)},children:k.label},k.label)),Pt&&e.jsx("button",{className:`filter-chip ${ue===""?"filter-chip-active":""}`,type:"button","aria-pressed":ue==="",onClick:()=>{z(""),re(!1)},children:"No location"}),Jt.length>1&&ue===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${ee?"filter-chip-active":""}`,type:"button","aria-pressed":ee,onClick:()=>re(k=>!k),title:"Side-by-side location comparison",children:"Compare"})]}),W&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-negative-900/40 bg-negative-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-negative-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-strong",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:W})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>K(null),children:"Clear filter ×"})]}),e.jsx(zu,{evidence:ls,compareLocations:ee})]}),e.jsxs(_a,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:J(),children:[e.jsx(Wm,{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(Xe,{text:"Per-model citation rate in the latest sweep. The same query set can perform differently across engines."})]})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Model"}),e.jsx("th",{scope:"col",children:"Citation rate"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(k=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(cn,{provider:k.provider}),k.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:k.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[k.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[k.cited," of ",k.total]})]},`${k.provider}::${k.model??"unknown"}`))})]})})]})]}),!J()&&e.jsx(_a,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(k=>e.jsx(Jd,{run:k},k.id))})})]}),report:ke,reportState:fe,onOpenSetup:J()?void 0:()=>{r({to:"/projects/$projectName/portfolio",params:{projectName:he}})},onRetryReport:()=>{mt===2?Promise.all([We.refetch(),$e.refetch()]):$e.refetch()},onViewChange:k=>{Le({scope:k.scope,...k.groupKey?{groupKey:k.groupKey}:{},queryClass:k.queryClass,...k.search?.trim()?{search:k.search.trim()}:{}})},onLoadMore:k=>{k===U?.properties.nextCursor&&We.fetchNextPage()},onPropertyExpand:()=>{Fe&&$e.isError&&$e.refetch(),Pe(!0)},onRetryEvidence:()=>{$e.refetch()},renderPropertyLink:mt===2&&!J()?({id:k,name:be})=>e.jsx(os,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:he,targetKey:k},className:"text-link hover:underline",children:be}):void 0,isViewLoading:We.isPlaceholderData,isLoadingMore:We.isFetchingNextPage,isLoadMoreError:We.isFetchNextPageError,viewSearch:Be.search??""},`${he}:${ot}`)]}):c==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(ig,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(k,be)=>{await Vt(k,be)},onRefresh:()=>{n()}}),e.jsx(lg,{project:s.project,onSave:async k=>{await Vt(s.project.name,k)}}),i&&!J()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),At==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):At==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ce.refetch()},children:"Retry"})]}):e.jsx(P,{type:"button",variant:"outline",onClick:()=>{r({to:"/projects/$projectName/portfolio",params:{projectName:he}})},children:qo(kt.setupAction)})]}):null,e.jsx(dg,{projectName:s.project.name}),e.jsx(mg,{projectName:s.project.name}),i&&!J()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),p?e.jsxs(de,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{type:"button",variant:"destructive",disabled:y,onClick:Me(ps),children:y?"Deleting...":"Yes, delete project"}),e.jsx(P,{type:"button",variant:"outline",disabled:y,onClick:()=>u(!1),children:"Cancel"})]})]}):e.jsxs(Ye,{type:"button",variant:"outline",onClick:()=>u(!0),children:[e.jsx(lu,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):c==="report"?e.jsx(Vp,{projectName:s.project.name}):c==="discovery"?e.jsx(Gh,{projectName:he}):c==="technical-aeo"?e.jsx(Zd,{projectName:s.project.name,projectId:s.project.id,initialRunId:g.siteHealthRunId,onReleaseInitialRun:C}):c==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(Rx,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(px,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):c==="history"?e.jsx(Kh,{projectName:s.project.name}):c==="activity"?e.jsx(cm,{projectName:s.project.name}):c==="backlinks"?e.jsx(Hm,{projectName:s.project.name}):c==="local"?e.jsx(Sm,{projectName:s.project.name,projectId:s.project.id}):c==="search-console"?e.jsx(pg,{projectName:s.project.name}):null]})}export{Mg as ProjectPage,hg as patchProjectDashboardCache};
|