@canonry/canonry 4.180.2 → 4.180.4

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.
Files changed (26) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +1 -1
  2. package/assets/assets/{AuditHistoryPanel-Cf-jEEKZ.js → AuditHistoryPanel-CdM_9qX1.js} +1 -1
  3. package/assets/assets/{BacklinksPage-oMcS6Hc_.js → BacklinksPage-DWWMPSPn.js} +1 -1
  4. package/assets/assets/{HistoryPage-CDQOpxi0.js → HistoryPage-m7TtGFBQ.js} +1 -1
  5. package/assets/assets/{MeasurementPropertyPage-MoKFTmrS.js → MeasurementPropertyPage-CYBfBtEz.js} +1 -1
  6. package/assets/assets/{ProjectPage-CtD1AwXE.js → ProjectPage-CNPcNrIR.js} +1 -1
  7. package/assets/assets/{RunRow-CPekiscK.js → RunRow-O4u505Fc.js} +1 -1
  8. package/assets/assets/{RunsPage-hn05ImCv.js → RunsPage-CCzFT4X0.js} +1 -1
  9. package/assets/assets/{SettingsPage-BOTYXtfF.js → SettingsPage-DOmE3JbU.js} +1 -1
  10. package/assets/assets/{SiteHealthSection-FwMZ11F8.js → SiteHealthSection-BZFVE2h9.js} +3 -3
  11. package/assets/assets/{TrafficPage-f2v6A_uk.js → TrafficPage-DYxOEVbW.js} +1 -1
  12. package/assets/assets/{TrafficSourceDetailPage-nhWRLHiu.js → TrafficSourceDetailPage-Qd5Zpx_8.js} +1 -1
  13. package/assets/assets/{extract-error-message-Cp1YeVEr.js → extract-error-message-B0bdIDVc.js} +1 -1
  14. package/assets/assets/{index-VmxEHABq.js → index-HmdbSL4h.js} +17 -17
  15. package/assets/assets/{react-sigma_core.esm.min-fnm2MkMi.js → react-sigma_core.esm.min-DXCrX1Ie.js} +1 -1
  16. package/assets/index.html +1 -1
  17. package/dist/{chunk-665YENL2.js → chunk-2J65ALIR.js} +23 -5
  18. package/dist/{chunk-4XHQ2GCN.js → chunk-DK23XZ6C.js} +2 -2
  19. package/dist/{chunk-DA25LOTW.js → chunk-JJIESVNL.js} +1 -1
  20. package/dist/{chunk-6IR32MIH.js → chunk-UESVOQRS.js} +10 -2
  21. package/dist/{chunk-44LVINXQ.js → chunk-V4QGOJNH.js} +681 -452
  22. package/dist/cli.js +17 -6
  23. package/dist/index.js +4 -4
  24. package/dist/{intelligence-service-RNBODYMZ.js → intelligence-service-XNAKDGDQ.js} +2 -2
  25. package/dist/mcp.js +3 -3
  26. package/package.json +11 -11
@@ -1,4 +1,4 @@
1
- import{r as l,j as e,u as Ie,L as os,n as Is,o as qt,B as Ei,C as Wo,h as Yo,k as Xo,D as Jo}from"./vendor-tanstack-Dock0eH1.js";import{M as qi,I as Xe,T as oe,t as Zo,a as el,u as Oi,C as tl,P as cn,B as P,h as sl,b as nl,c as al,d as Gs,g as Gi,e as Fi,f as de,i as V,j as J,k as ft,l as Me,m as rl,n as il,o as ol,p as _i,q as ll,r as cl,S as _s,s as dl,v as ul,w as qs,x as Ot,y as ml,z as Sr,A as Ui,G as Tt,D as er,E as hl,F as xl,H as pl,J as gl,K as Cr,L as Se,N as fl,O as bl,Q as ha,R as yl,U as vl,V as jl,W as Nl,X as wl,Y as Sl,Z as Cl,_ as kl,$ as Al,a0 as Pl,a1 as Rl,a2 as Il,a3 as Tl,a4 as $l,a5 as Ml,a6 as Bi,a7 as Ks,a8 as Ll,a9 as Vi,aa as Qn,ab as Dl,ac as Ye,ad as El,ae as ql,af as Ol,ag as Hn,ah as Gl,ai as Fl,aj as _l,ak as dn,al as Ul,am as Bl,an as Vl,ao as Ki,ap as Ua,aq as Kl,ar as zi,as as zl,at as tr,au as Ql,av as Hl,aw as Wl,ax as Yl,ay as Xl,az as Jl,aA as Zl,aB as Nn,aC as Us,aD as ec,aE as tc,aF as sc,aG as nc,aH as Qi,aI as ac,aJ as rc,aK as ic,aL as oc,aM as lc,aN as Hi,aO as cc,aP as dc,aQ as uc,aR as mc,aS as hc,aT as xc,aU as pc,aV as gc,aW as fc,aX as bc,aY as yc,aZ as vc,a_ as jc,a$ as Nc,b0 as wc,b1 as Sc,b2 as Cc,b3 as kc,b4 as Ac,b5 as Pc,b6 as rs,b7 as Rc,b8 as it,b9 as Ic,ba as Tc,bb as $c,bc as Mc,bd as Lc,be as Dc,bf as Ec,bg as qc,bh as Oc,bi as Gc,bj as Fc,bk as _c,bl as Uc,bm as Bc,bn as Vc,bo as Kc,bp as zc,bq as Qc,br as Hc,bs as Wc,bt as Yc,bu as Xc,bv as Jc,bw as Zc,bx as ed,by as td,bz as sd,bA as nd,bB as ad,bC as rd,bD as id,bE as od,bF as ld,bG as cd,bH as dd,bI as ud,bJ as md,bK as hd,bL as xa,bM as xd,bN as pd,bO as kr,bP as gd,bQ as fd,bR as bd,bS as yd,bT as vd,bU as jd,bV as Nd,bW as wd,bX as Sd,bY as Cd,bZ as kd,b_ as Ad,b$ as Wi,c0 as Pd,c1 as Rd,c2 as Id,c3 as Td,c4 as $d,c5 as Md,c6 as Ld,c7 as Ar,c8 as Dd,c9 as pa,ca as Ed,cb as qd,cc as Od,cd as Gd,ce as Fd,cf as _d,cg as Ud,ch as Yi,ci as Bd,cj as Vd,ck as Kd,cl as zd,cm as Qd,cn as Hd,co as Tn,cp as Wd,cq as Yd,cr as Xd,cs as Pr,ct as Jd}from"./index-VmxEHABq.js";import{R as Zd}from"./RunRow-CPekiscK.js";import{u as Sn,D as rn,a as Bs,b as Xi,M as Kn,c as ds,S as eu}from"./SiteHealthSection-FwMZ11F8.js";import{e as tu,q as Wn,U as su,r as nu,L as au,s as Ji,i as ru,P as Yn,D as Zi,t as iu,u as ou,E as lu,C as Xn,v as cu}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 Vs,M as eo,i as to,o as xs,j as Ps,p as du}from"./ChartPrimitives-DG35TyhH.js";import{u as uu,a as mu,b as hu,t as xu,e as pu,c as ut}from"./extract-error-message-Cp1YeVEr.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 Fs,e as gu}from"./vendor-recharts-D8rt5lKn.js";import{A as fu}from"./AuditHistoryPanel-Cf-jEEKZ.js";import{a as bu,b as yu}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function Rs(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 vu(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=ju(r,1));return a}function ju(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 Nu(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 wu(t,s){const n=Nu(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} (${Rs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Rs(t.prior)} ${s})`:`Flat ${n} (${Rs(t.prior)} ${s})`}const so=30;function Rr(t){return Math.round(t*10)/10}function Su(t){return t.prior>=so&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Rr(t.deltaAbs)} vs ${Rr(t.prior)}`}function Cu(t,s,n){return t.prior>=so&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Rs(Math.round(t.deltaAbs))} ${s} ${n}`}const ku=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function no(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function ao(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 ro(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(no).map(ao).filter(Boolean)):new Set}function io(t,s){const n=no(t).map(ao).filter(Boolean).filter(a=>!ku.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Au(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Pu(t,s){const n=ro(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=io(Au(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function Ru(t){const s=ro(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=io(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const Iu=1e6;function Tu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/Iu)}const oo={queryClass:"all"},$u=["all","non-brand","branded"];function Mu(t){return typeof t=="string"&&$u.includes(t)}function Lu(t){const s=Mu(t.class)?t.class:oo.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 Du(t,s){return s===null||t===null?!1:t!==s}function Eu(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===oo.queryClass?void 0:t.queryClass}}const $s=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Ir={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},qu={"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."},Ou="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Gu(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 Fu({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:Ou})]}),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 _u({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=Gu(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"?qi[t.tone]:"text-secondary";function b(g){const f=$s.findIndex(O=>O.value===c);let C=null;g.key==="ArrowRight"||g.key==="ArrowDown"?C=(f+1)%$s.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?C=(f-1+$s.length)%$s.length:g.key==="Home"?C=0:g.key==="End"&&(C=$s.length-1),C!==null&&(g.preventDefault(),r($s[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:qu[h]})]}),m?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:b,children:$s.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(Fu,{breakdown:p,projectLabel:s,competitorDomains:n})]})}function Va({state:t,label:s}){return e.jsx(oe,{tone:el(t),children:s??Zo(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 Uu=320;function Bu(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 Vu(t,s){return t.map(n=>lo(n,s))}function lo(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 Ku(t){const s=Ka(Vu(t,"mentions")),n=Ka(t);return[Dr(s,"mentions"),Dr(n,"citations")]}function zu({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:Ku(t).map(s=>e.jsx(zu,{signal:s},s.key))})}function Qu({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Oi(),[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(lo(E,i)),S.rawItems.push(E),O.set(j,S)}return[...O.values()]},[t,i,s]),u=Sn({rows:p,getSearchText:Bu}),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===tl.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(tu,{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(Yu,{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(Bs,{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 Hu(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=nl(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 Wu(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 Yu({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}=Wu(t.answerSnippet,Uu),o=Hu(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:sl(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 Xu({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:al(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],Ju=["both","server","ga4"],Fr={fontSize:11,paddingTop:6},_r=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Ur=t=>typeof t=="number"?Rs(Math.round(t)):String(t),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 Zu(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 em({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,m]=l.useState("both"),c=uu(t,{sinceMinutes:s,granularity:"day",limit:1}),h=mu(t),u=Ie({...Gi({client:V,path:{name:t}}),enabled:!!t,staleTime:Gs}).data?.connected===!0,y=Ie({...Fi({client:V,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&u,staleTime:Gs}),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:Rs(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:Rs(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:Rs(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,formatter:Ur}),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(Fs,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:fa,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Fs,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",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:Ju,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,formatter:Ur}),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(Fs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Or,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Fs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Gr,strokeWidth:1.8,strokeDasharray:"5 3",dot:Zu(O.map(q=>q.ga4Visits),Gr)}),r&&i!=="ga4"&&e.jsx(Fs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Or,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const tm=6,un="__other__",on="_socialTotal";function sm(t,s=tm){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 co(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Br="_totalSessions",Vr="_organicSessions";function nm(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Br]:i.sessions,[Vr]:i.organicSessions});for(const i of t.days){let m=n.get(i.date);m||(m={[Br]:0,[Vr]: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 am=["7d","30d","90d"],rm={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ss=nt,za=Xt.textDim,uo=Xt.textFaint,pn=25;function im(t){return Xi(t.landingPage)}const om=25,lm=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 mo(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 cm({projectName:t}){const{data:s,isLoading:n,isError:a}=hu(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:xu(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?mo(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 dm({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(cm,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(ra,{windows:am,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(em,{projectName:t,sinceMinutes:rm[s]}),e.jsx(um,{projectName:t,window:s})]})}function um({projectName:t,window:s}){const n=Is(),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({...Gi({client:V,path:{name:t}}),staleTime:Gs});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({...rl({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Gs}).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({...Fi({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Gs}).catch(()=>ja),n.fetchQuery({...il({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Gs}).catch(()=>[]),n.fetchQuery({...ol({client:V,path:{name:t},query:Lt}),staleTime:Gs}).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 _i(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 ll(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=>Xi(U.landingPage),pageSize:lm}),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:im,pageSize:om}),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=sm(R);return{socialChartData:U.data,socialChartSources:U.sources,socialOtherCount:U.otherCount}},[R]),{chartData:M,chartSources:L,dateRange:je}=l.useMemo(()=>{const U=nm(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(mm,{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(su,{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(xm,{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(pm,{row:U},`${U.landingPage}:${U.source}:${U.medium}:${U.sourceDimension}`))})]})}),e.jsx(Bs,{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:co(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:uo,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(fm,{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(gm,{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(hm,{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(Bs,{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 ${mo(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function mm({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 cl(t,{propertyId:n.trim(),keyJson:i});try{await _i(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(nu,{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 ho={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 ${ho[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 ${ho[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function hm({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 xo={session:"Session",first_user:"First Visit",manual_utm:"UTM"},po={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 xm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=xo[t.sourceDimension]??t.sourceDimension,r=po[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 pm({row:t}){const s=xo[t.sourceDimension]??t.sourceDimension,n=po[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 gm({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 fm({sources:t,otherCount:s}){const n=[{key:on,color:uo,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:co(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 bm(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 ym=["7d","30d","90d","all"],Ln=500,Kr=[{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:Vs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],js=25,vm="canonry:google-oauth-complete",jm=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Nm(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%":`${jm.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function wm(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,m=`${r.startDate} to ${r.endDate}`,c=`Tile percentages compare these ${s} ${o} (${m}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?c:`${c} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function zr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Qr(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 Hr(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Sm({projectName:t,refreshNonce:s}){const n=Is(),[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===_s.CTR?Number.isFinite(Z.ctr)?Z.ctr:0:Z[x],Je=x===_s.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 Go(x,D){const Z=pu(x),le=bm(Z);le?(cs(le),Re(null)):(cs(null),Re(Z.message||D))}const Ut=o.find(x=>x.connectionType==="gsc"),Ts=(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,Fo=hr===1?"Resubmit sitemap index":hr>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",_o=h.length>0||v.length>0||g.length>0,la=dl(),ca=ul();async function xr(x,D=!1){if(!x){c([]),A("");return}_e(!0);try{const{sites:Z}=await n.fetchQuery({...Cl({client:V,path:{name:t}}),staleTime:D?0:Tt});c(Z),A(x.propertyId??Z[0]?.siteUrl??""),cs(null)}catch(Z){c([]),Go(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({...xl({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({...hl({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({...wl({client:V,path:{name:t},query:Z}),staleTime:x?0:Tt}),n.fetchQuery({...Sl({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({...fl({client:V,path:{name:t}}),staleTime:x?0:Tt}),n.fetchQuery({...bl({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 Uo(){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(yl({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 Bo(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(!Ts||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 vl(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 Vo(){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 jl(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([Ui().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!==vm||ys.connectionType!=="gsc"||st(!0)};const{authUrl:D,redirectUri:Z}=await gl(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 Ko(){Re(null),es(null);try{await pl(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 zo(){if(E){Te(!0),Re(null);try{await kl(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 Qo(){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 Nl(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}),(qs(gt.enableUrl)||qs(gt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[qs(gt.enableUrl)&&e.jsx("a",{href:qs(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 ↗"}),qs(gt.indexingApiUrl)&&e.jsx("a",{href:qs(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(Ko),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||_o)&&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:`${wm(u?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${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:ym,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=Kr.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?[]:vu(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:Kr.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(Ho=>Ho!==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:Nm(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(eo,{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(_s).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:[ml[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(Bs,{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:()=>{Uo()},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:Vs.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(Bs,{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:!Ts||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:!Ts||ct||oa.length===0,onClick:()=>{Zs(oa)},children:ct?"Resubmitting…":Fo}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Ts||ct||!xt?.length,onClick:()=>{Vo()},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]})]}),!Ts&&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=zr(x),Z=Qr(x),le=Hr(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:()=>{Bo(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:!Ts||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:Hr(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:zr(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Qr(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:!Ts||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(Bs,{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(zo),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(Qo),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 Cm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function km({projectName:t,projectId:s}){const n=Is(),[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({...Al({client:V,path:{name:t}}),enabled:u}),b=Ie({...Pl({client:V,path:{name:t},query:y}),enabled:u}),g=Ie({...Rl({client:V,path:{name:t},query:y}),enabled:u}),f=Ie({...Il({client:V,path:{name:t},query:y}),enabled:u}),C=Ie({...Tl({client:V,path:{name:t},query:y}),enabled:u}),O=Ie({...$l({client:V,path:{name:t},query:y}),enabled:u}),E=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>Ml(t),enabled:u});function A(){ft(n,"gbp")}const d=qt({...Ll(),onSuccess:B=>{Bi({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(Vi,Qn,Qn),S=Object.values(j.runs).some(B=>B.kind===Ks["gbp-sync"]&&B.projectId===s),q=d.isPending||S,_=qt({...Dl(),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&&Cm.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",Gm(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(Bm,{performance:N.performance,freshness:N.freshness,timeseries:N.timeseries}),N?.profileCompleteness&&e.jsx(Am,{summary:N.profileCompleteness}),re.length>0&&e.jsx(Pm,{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 Am({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 ${Om(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Pm({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:go(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Im,{location:h})}),e.jsx("td",{children:e.jsx(Tm,{lodging:p})}),e.jsx("td",{children:e.jsx(Mm,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Dm,{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(qm,{location:h,lodging:p,place:u,placeActions:y})})})]},h.id)})})]})})]})}function Rm(t){return[{label:"Description",tone:Os(t.description)?"positive":"neutral",value:Os(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Os(t.primaryPhone)?"positive":"neutral",value:Os(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Os(t.websiteUri)?"positive":"neutral",value:Os(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 Im({location:t}){const s=Rm(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 Tm({lodging:t}){return e.jsx(sr,{...$m(t)})}function $m(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 Mm({place:t,mapsUri:s}){return e.jsx(sr,{...Lm(t,s)})}function Lm(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 Dm({actions:t}){return e.jsx(sr,{...Em(t)})}function Em(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 qm({location:t,lodging:s,place:n,placeActions:a}){const r=s?_m(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:Os(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:go(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:Wr(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:Wr(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?` · ${Fm(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 Om(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Gm(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Os(t){return typeof t=="string"&&t.trim().length>0}function go(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 Fm(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Wr(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function _m(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Um(n)).map(([s])=>ta(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Um(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Bm({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=El.filter(b=>(a[b]??0)>0),o=ql.filter(b=>(a[b]??0)>0),i=Object.keys(a).filter(b=>(a[b]??0)>0&&Ol(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(Yr,{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(Yr,{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 Yr({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(Fs,{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 Vm(t){return to(xs(String(t)))}function Km(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(iu,{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 zm(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Qm(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 Hm(t){const s=t.filter(n=>n.kind===Ks["backlink-extract"]&&!Ki(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Wm(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 Ym({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([Gl().catch(()=>null),Fl(t,{excludeCrawlers:!0}).catch(()=>null),_l(t,{limit:Dn,offset:g,excludeCrawlers:!0}).catch(se=>{if(se instanceof dn&&se.code==="NOT_FOUND")return null;throw se}),Ul(t).catch(()=>[]),Bl(t).catch(()=>[])]);c(z),n(ee),r(re),i(W);const R=Hm(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;Ki(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 Kl(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(au,{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:[Wm(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(Ji,{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:Vl(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(Zi,{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(ru,{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:zm(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 ",Qm(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:Vm}),e.jsx(Ys,{tick:Gt,stroke:ss,allowDecimals:!1}),e.jsx(Xs,{contentStyle:Wt.contentStyle,labelStyle:Wt.labelStyle,itemStyle:Wt.itemStyle,labelFormatter:Km}),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(Bs,{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 Xm({projectName:t}){const s=Ie({...zl({client:V,path:{name:t}}),staleTime:zi}),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(Jm,{data:n}),e.jsx(Zm,{data:n}),n.competitorGaps.length>0&&e.jsx(nh,{data:n})]})}function Jm({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 Zm({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(eh,{}),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(ou,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(th,{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 eh(){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 th({provider:t}){const s=sh(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 sh(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 nh({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 fo(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=fo(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 ah(t){const s=fo(t);return s?to(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 rh(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 bo(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function ih(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function oh(t){return t.servedModelAttribution??{}}function lh(t){return t.modelServiceMismatch??{}}function ch(t){return t.modelPointerChanges??{}}function dh(t){return t.length>0?t.join(", "):null}function Xr(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 uh(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Xr(Ha(a),s))continue;const r=bo(a);return r?Xr(r,s)??null:null}return null}function mh(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 hh(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:mh(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function xh(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 ph(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 gh(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 fh(t,s,n){return s==="mentionShare"?gh(t):rh(t,s,n)}function Jr(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 Zr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function ei(t){return t>0?`+${t}`:`${t}`}function bh(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${ei(n.delta)} on ${Zr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${ei(s.delta)} on ${Zr(s.date)})`}const yh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],vh=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],jh=[{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],Nh="var(--chart-tooltip-bg)",wh={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function hs(t){const s=mn(t);return wh[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ks(t){return Math.round(t*10)/10}function Sh(t){return t===An||t===Pn||t===Yt}function yo(t){return t===An?"Cited":t===Pn?"Mentioned":t===Yt?"Mention share":hs(t)}function yn(t,s){return t===An?Vs.positive:t===Pn?nt[1]:t===Yt?nr:du(mn(t),s)}function Ch(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function kh(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
1
+ import{r as l,j as e,u as Ie,L as os,n as Is,o as qt,B as Ei,C as Wo,h as Yo,k as Xo,D as Jo}from"./vendor-tanstack-Dock0eH1.js";import{M as qi,I as Xe,T as oe,t as Zo,a as el,u as Oi,C as tl,P as cn,B as P,h as sl,b as nl,c as al,d as Gs,g as Gi,e as Fi,f as de,i as V,j as J,k as ft,l as Me,m as rl,n as il,o as ol,p as _i,q as ll,r as cl,S as _s,s as dl,v as ul,w as qs,x as Ot,y as ml,z as Sr,A as Ui,G as Tt,D as er,E as hl,F as xl,H as pl,J as gl,K as Cr,L as Se,N as fl,O as bl,Q as ha,R as yl,U as vl,V as jl,W as Nl,X as wl,Y as Sl,Z as Cl,_ as kl,$ as Al,a0 as Pl,a1 as Rl,a2 as Il,a3 as Tl,a4 as $l,a5 as Ml,a6 as Bi,a7 as Ks,a8 as Ll,a9 as Vi,aa as Qn,ab as Dl,ac as Ye,ad as El,ae as ql,af as Ol,ag as Hn,ah as Gl,ai as Fl,aj as _l,ak as dn,al as Ul,am as Bl,an as Vl,ao as Ki,ap as Ua,aq as Kl,ar as zi,as as zl,at as tr,au as Ql,av as Hl,aw as Wl,ax as Yl,ay as Xl,az as Jl,aA as Zl,aB as Nn,aC as Us,aD as ec,aE as tc,aF as sc,aG as nc,aH as Qi,aI as ac,aJ as rc,aK as ic,aL as oc,aM as lc,aN as Hi,aO as cc,aP as dc,aQ as uc,aR as mc,aS as hc,aT as xc,aU as pc,aV as gc,aW as fc,aX as bc,aY as yc,aZ as vc,a_ as jc,a$ as Nc,b0 as wc,b1 as Sc,b2 as Cc,b3 as kc,b4 as Ac,b5 as Pc,b6 as rs,b7 as Rc,b8 as it,b9 as Ic,ba as Tc,bb as $c,bc as Mc,bd as Lc,be as Dc,bf as Ec,bg as qc,bh as Oc,bi as Gc,bj as Fc,bk as _c,bl as Uc,bm as Bc,bn as Vc,bo as Kc,bp as zc,bq as Qc,br as Hc,bs as Wc,bt as Yc,bu as Xc,bv as Jc,bw as Zc,bx as ed,by as td,bz as sd,bA as nd,bB as ad,bC as rd,bD as id,bE as od,bF as ld,bG as cd,bH as dd,bI as ud,bJ as md,bK as hd,bL as xa,bM as xd,bN as pd,bO as kr,bP as gd,bQ as fd,bR as bd,bS as yd,bT as vd,bU as jd,bV as Nd,bW as wd,bX as Sd,bY as Cd,bZ as kd,b_ as Ad,b$ as Wi,c0 as Pd,c1 as Rd,c2 as Id,c3 as Td,c4 as $d,c5 as Md,c6 as Ld,c7 as Ar,c8 as Dd,c9 as pa,ca as Ed,cb as qd,cc as Od,cd as Gd,ce as Fd,cf as _d,cg as Ud,ch as Yi,ci as Bd,cj as Vd,ck as Kd,cl as zd,cm as Qd,cn as Hd,co as Tn,cp as Wd,cq as Yd,cr as Xd,cs as Pr,ct as Jd}from"./index-HmdbSL4h.js";import{R as Zd}from"./RunRow-O4u505Fc.js";import{u as Sn,D as rn,a as Bs,b as Xi,M as Kn,c as ds,S as eu}from"./SiteHealthSection-BZFVE2h9.js";import{e as tu,q as Wn,U as su,r as nu,L as au,s as Ji,i as ru,P as Yn,D as Zi,t as iu,u as ou,E as lu,C as Xn,v as cu}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 Vs,M as eo,i as to,o as xs,j as Ps,p as du}from"./ChartPrimitives-DG35TyhH.js";import{u as uu,a as mu,b as hu,t as xu,e as pu,c as ut}from"./extract-error-message-B0bdIDVc.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 Fs,e as gu}from"./vendor-recharts-D8rt5lKn.js";import{A as fu}from"./AuditHistoryPanel-CdM_9qX1.js";import{a as bu,b as yu}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function Rs(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 vu(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=ju(r,1));return a}function ju(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 Nu(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 wu(t,s){const n=Nu(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} (${Rs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Rs(t.prior)} ${s})`:`Flat ${n} (${Rs(t.prior)} ${s})`}const so=30;function Rr(t){return Math.round(t*10)/10}function Su(t){return t.prior>=so&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Rr(t.deltaAbs)} vs ${Rr(t.prior)}`}function Cu(t,s,n){return t.prior>=so&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Rs(Math.round(t.deltaAbs))} ${s} ${n}`}const ku=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function no(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function ao(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 ro(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(no).map(ao).filter(Boolean)):new Set}function io(t,s){const n=no(t).map(ao).filter(Boolean).filter(a=>!ku.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Au(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Pu(t,s){const n=ro(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=io(Au(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function Ru(t){const s=ro(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=io(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const Iu=1e6;function Tu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/Iu)}const oo={queryClass:"all"},$u=["all","non-brand","branded"];function Mu(t){return typeof t=="string"&&$u.includes(t)}function Lu(t){const s=Mu(t.class)?t.class:oo.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 Du(t,s){return s===null||t===null?!1:t!==s}function Eu(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===oo.queryClass?void 0:t.queryClass}}const $s=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Ir={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},qu={"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."},Ou="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Gu(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 Fu({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:Ou})]}),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 _u({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=Gu(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"?qi[t.tone]:"text-secondary";function b(g){const f=$s.findIndex(O=>O.value===c);let C=null;g.key==="ArrowRight"||g.key==="ArrowDown"?C=(f+1)%$s.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?C=(f-1+$s.length)%$s.length:g.key==="Home"?C=0:g.key==="End"&&(C=$s.length-1),C!==null&&(g.preventDefault(),r($s[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:qu[h]})]}),m?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:b,children:$s.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(Fu,{breakdown:p,projectLabel:s,competitorDomains:n})]})}function Va({state:t,label:s}){return e.jsx(oe,{tone:el(t),children:s??Zo(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 Uu=320;function Bu(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 Vu(t,s){return t.map(n=>lo(n,s))}function lo(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 Ku(t){const s=Ka(Vu(t,"mentions")),n=Ka(t);return[Dr(s,"mentions"),Dr(n,"citations")]}function zu({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:Ku(t).map(s=>e.jsx(zu,{signal:s},s.key))})}function Qu({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Oi(),[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(lo(E,i)),S.rawItems.push(E),O.set(j,S)}return[...O.values()]},[t,i,s]),u=Sn({rows:p,getSearchText:Bu}),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===tl.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(tu,{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(Yu,{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(Bs,{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 Hu(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=nl(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 Wu(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 Yu({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}=Wu(t.answerSnippet,Uu),o=Hu(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:sl(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 Xu({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:al(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],Ju=["both","server","ga4"],Fr={fontSize:11,paddingTop:6},_r=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Ur=t=>typeof t=="number"?Rs(Math.round(t)):String(t),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 Zu(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 em({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,m]=l.useState("both"),c=uu(t,{sinceMinutes:s,granularity:"day",limit:1}),h=mu(t),u=Ie({...Gi({client:V,path:{name:t}}),enabled:!!t,staleTime:Gs}).data?.connected===!0,y=Ie({...Fi({client:V,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&u,staleTime:Gs}),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:Rs(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:Rs(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:Rs(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,formatter:Ur}),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(Fs,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:fa,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Fs,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",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:Ju,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,formatter:Ur}),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(Fs,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Or,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Fs,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:Gr,strokeWidth:1.8,strokeDasharray:"5 3",dot:Zu(O.map(q=>q.ga4Visits),Gr)}),r&&i!=="ga4"&&e.jsx(Fs,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Or,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const tm=6,un="__other__",on="_socialTotal";function sm(t,s=tm){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 co(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Br="_totalSessions",Vr="_organicSessions";function nm(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Br]:i.sessions,[Vr]:i.organicSessions});for(const i of t.days){let m=n.get(i.date);m||(m={[Br]:0,[Vr]: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 am=["7d","30d","90d"],rm={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Ss=nt,za=Xt.textDim,uo=Xt.textFaint,pn=25;function im(t){return Xi(t.landingPage)}const om=25,lm=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 mo(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 cm({projectName:t}){const{data:s,isLoading:n,isError:a}=hu(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:xu(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?mo(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 dm({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(cm,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(ra,{windows:am,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(um,{projectName:t,window:s}),e.jsx(em,{projectName:t,sinceMinutes:rm[s]})]})}function um({projectName:t,window:s}){const n=Is(),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({...Gi({client:V,path:{name:t}}),staleTime:Gs});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({...rl({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Gs}).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({...Fi({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Gs}).catch(()=>ja),n.fetchQuery({...il({client:V,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:Gs}).catch(()=>[]),n.fetchQuery({...ol({client:V,path:{name:t},query:Lt}),staleTime:Gs}).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 _i(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 ll(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=>Xi(U.landingPage),pageSize:lm}),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:im,pageSize:om}),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=sm(R);return{socialChartData:U.data,socialChartSources:U.sources,socialOtherCount:U.otherCount}},[R]),{chartData:M,chartSources:L,dateRange:je}=l.useMemo(()=>{const U=nm(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(mm,{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(su,{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(xm,{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(pm,{row:U},`${U.landingPage}:${U.source}:${U.medium}:${U.sourceDimension}`))})]})}),e.jsx(Bs,{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:co(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:uo,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(fm,{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(gm,{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(hm,{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(Bs,{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 ${mo(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function mm({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 cl(t,{propertyId:n.trim(),keyJson:i});try{await _i(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(nu,{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 ho={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 ${ho[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 ${ho[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function hm({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 xo={session:"Session",first_user:"First Visit",manual_utm:"UTM"},po={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 xm({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=xo[t.sourceDimension]??t.sourceDimension,r=po[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 pm({row:t}){const s=xo[t.sourceDimension]??t.sourceDimension,n=po[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 gm({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 fm({sources:t,otherCount:s}){const n=[{key:on,color:uo,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:co(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 bm(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 ym=["7d","30d","90d","all"],Ln=500,Kr=[{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:Vs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],js=25,vm="canonry:google-oauth-complete",jm=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Nm(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%":`${jm.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function wm(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,m=`${r.startDate} to ${r.endDate}`,c=`Tile percentages compare these ${s} ${o} (${m}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?c:`${c} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function zr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Qr(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 Hr(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Sm({projectName:t,refreshNonce:s}){const n=Is(),[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===_s.CTR?Number.isFinite(Z.ctr)?Z.ctr:0:Z[x],Je=x===_s.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 Go(x,D){const Z=pu(x),le=bm(Z);le?(cs(le),Re(null)):(cs(null),Re(Z.message||D))}const Ut=o.find(x=>x.connectionType==="gsc"),Ts=(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,Fo=hr===1?"Resubmit sitemap index":hr>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",_o=h.length>0||v.length>0||g.length>0,la=dl(),ca=ul();async function xr(x,D=!1){if(!x){c([]),A("");return}_e(!0);try{const{sites:Z}=await n.fetchQuery({...Cl({client:V,path:{name:t}}),staleTime:D?0:Tt});c(Z),A(x.propertyId??Z[0]?.siteUrl??""),cs(null)}catch(Z){c([]),Go(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({...xl({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({...hl({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({...wl({client:V,path:{name:t},query:Z}),staleTime:x?0:Tt}),n.fetchQuery({...Sl({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({...fl({client:V,path:{name:t}}),staleTime:x?0:Tt}),n.fetchQuery({...bl({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 Uo(){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(yl({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 Bo(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(!Ts||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 vl(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 Vo(){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 jl(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([Ui().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!==vm||ys.connectionType!=="gsc"||st(!0)};const{authUrl:D,redirectUri:Z}=await gl(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 Ko(){Re(null),es(null);try{await pl(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 zo(){if(E){Te(!0),Re(null);try{await kl(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 Qo(){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 Nl(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}),(qs(gt.enableUrl)||qs(gt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[qs(gt.enableUrl)&&e.jsx("a",{href:qs(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 ↗"}),qs(gt.indexingApiUrl)&&e.jsx("a",{href:qs(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(Ko),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||_o)&&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:`${wm(u?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${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:ym,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=Kr.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?[]:vu(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:Kr.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(Ho=>Ho!==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:Nm(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(eo,{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(_s).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:[ml[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(Bs,{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:()=>{Uo()},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:Vs.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(Bs,{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:!Ts||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:!Ts||ct||oa.length===0,onClick:()=>{Zs(oa)},children:ct?"Resubmitting…":Fo}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!Ts||ct||!xt?.length,onClick:()=>{Vo()},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]})]}),!Ts&&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=zr(x),Z=Qr(x),le=Hr(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:()=>{Bo(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:!Ts||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:Hr(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:zr(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Qr(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:!Ts||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(Bs,{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(zo),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(Qo),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 Cm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function km({projectName:t,projectId:s}){const n=Is(),[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({...Al({client:V,path:{name:t}}),enabled:u}),b=Ie({...Pl({client:V,path:{name:t},query:y}),enabled:u}),g=Ie({...Rl({client:V,path:{name:t},query:y}),enabled:u}),f=Ie({...Il({client:V,path:{name:t},query:y}),enabled:u}),C=Ie({...Tl({client:V,path:{name:t},query:y}),enabled:u}),O=Ie({...$l({client:V,path:{name:t},query:y}),enabled:u}),E=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>Ml(t),enabled:u});function A(){ft(n,"gbp")}const d=qt({...Ll(),onSuccess:B=>{Bi({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(Vi,Qn,Qn),S=Object.values(j.runs).some(B=>B.kind===Ks["gbp-sync"]&&B.projectId===s),q=d.isPending||S,_=qt({...Dl(),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&&Cm.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",Gm(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(Bm,{performance:N.performance,freshness:N.freshness,timeseries:N.timeseries}),N?.profileCompleteness&&e.jsx(Am,{summary:N.profileCompleteness}),re.length>0&&e.jsx(Pm,{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 Am({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 ${Om(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Pm({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:go(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Im,{location:h})}),e.jsx("td",{children:e.jsx(Tm,{lodging:p})}),e.jsx("td",{children:e.jsx(Mm,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Dm,{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(qm,{location:h,lodging:p,place:u,placeActions:y})})})]},h.id)})})]})})]})}function Rm(t){return[{label:"Description",tone:Os(t.description)?"positive":"neutral",value:Os(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Os(t.primaryPhone)?"positive":"neutral",value:Os(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Os(t.websiteUri)?"positive":"neutral",value:Os(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 Im({location:t}){const s=Rm(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 Tm({lodging:t}){return e.jsx(sr,{...$m(t)})}function $m(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 Mm({place:t,mapsUri:s}){return e.jsx(sr,{...Lm(t,s)})}function Lm(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 Dm({actions:t}){return e.jsx(sr,{...Em(t)})}function Em(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 qm({location:t,lodging:s,place:n,placeActions:a}){const r=s?_m(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:Os(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:go(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:Wr(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:Wr(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?` · ${Fm(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 Om(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Gm(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Os(t){return typeof t=="string"&&t.trim().length>0}function go(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 Fm(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Wr(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function _m(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Um(n)).map(([s])=>ta(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Um(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Bm({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=El.filter(b=>(a[b]??0)>0),o=ql.filter(b=>(a[b]??0)>0),i=Object.keys(a).filter(b=>(a[b]??0)>0&&Ol(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(Yr,{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(Yr,{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 Yr({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(Fs,{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 Vm(t){return to(xs(String(t)))}function Km(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(iu,{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 zm(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Qm(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 Hm(t){const s=t.filter(n=>n.kind===Ks["backlink-extract"]&&!Ki(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Wm(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 Ym({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([Gl().catch(()=>null),Fl(t,{excludeCrawlers:!0}).catch(()=>null),_l(t,{limit:Dn,offset:g,excludeCrawlers:!0}).catch(se=>{if(se instanceof dn&&se.code==="NOT_FOUND")return null;throw se}),Ul(t).catch(()=>[]),Bl(t).catch(()=>[])]);c(z),n(ee),r(re),i(W);const R=Hm(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;Ki(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 Kl(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(au,{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:[Wm(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(Ji,{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:Vl(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(Zi,{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(ru,{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:zm(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 ",Qm(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:Vm}),e.jsx(Ys,{tick:Gt,stroke:ss,allowDecimals:!1}),e.jsx(Xs,{contentStyle:Wt.contentStyle,labelStyle:Wt.labelStyle,itemStyle:Wt.itemStyle,labelFormatter:Km}),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(Bs,{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 Xm({projectName:t}){const s=Ie({...zl({client:V,path:{name:t}}),staleTime:zi}),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(Jm,{data:n}),e.jsx(Zm,{data:n}),n.competitorGaps.length>0&&e.jsx(nh,{data:n})]})}function Jm({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 Zm({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(eh,{}),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(ou,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(th,{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 eh(){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 th({provider:t}){const s=sh(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 sh(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 nh({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 fo(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=fo(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 ah(t){const s=fo(t);return s?to(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 rh(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 bo(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function ih(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function oh(t){return t.servedModelAttribution??{}}function lh(t){return t.modelServiceMismatch??{}}function ch(t){return t.modelPointerChanges??{}}function dh(t){return t.length>0?t.join(", "):null}function Xr(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 uh(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Xr(Ha(a),s))continue;const r=bo(a);return r?Xr(r,s)??null:null}return null}function mh(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 hh(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:mh(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function xh(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 ph(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 gh(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 fh(t,s,n){return s==="mentionShare"?gh(t):rh(t,s,n)}function Jr(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 Zr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function ei(t){return t>0?`+${t}`:`${t}`}function bh(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${ei(n.delta)} on ${Zr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${ei(s.delta)} on ${Zr(s.date)})`}const yh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],vh=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],jh=[{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],Nh="var(--chart-tooltip-bg)",wh={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function hs(t){const s=mn(t);return wh[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ks(t){return Math.round(t*10)/10}function Sh(t){return t===An||t===Pn||t===Yt}function yo(t){return t===An?"Cited":t===Pn?"Mentioned":t===Yt?"Mention share":hs(t)}function yn(t,s){return t===An?Vs.positive:t===Pn?nt[1]:t===Yt?nr:du(mn(t),s)}function Ch(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function kh(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
2
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 vo(t,s){return s==="cited"?t.cited:t.mentionedCount}function jo(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 No(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=bo(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 Ah(t){return t.some(({event:s})=>s.to.status==="mixed")?Vs.caution:t.some(({event:s})=>s.to.status==="unknown")?Vs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:Vs.positive}function Ph(t,s,n){const a=No(t,s);return a?sa(a):Ps(xs(n))}function Rh({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:Ph(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=dh(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 ti(t){return t===null?"no data":`${t}%`}function ka(t){return t==null?"undefined":`${ks(t*100)}%`}function Ih({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=No(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:ti(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"?jo(i,p,a):null,y=u?.count??vo(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:yo(p)}),e.jsx("span",{className:"trend-tooltip-value",children:ti(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 Th({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=jo(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()}, ${vo(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 $h({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(()=>kh(s),[s]),p=Ie({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>Ql(t,a),staleTime:zi}),u=p.data??null,y=p.error,v=o==="mentionShare"?"overall":m,b=l.useMemo(()=>u?fh(u,o,v):null,[u,o,v]),g=u?ih(u):null,f=l.useMemo(()=>hh(g??{}),[g]),C=l.useMemo(()=>xh(g??{}),[g]),O=l.useMemo(()=>ph(g??{}),[g]),E=l.useMemo(()=>Object.entries(g??{}).filter(([,K])=>K.anchorUnavailable).map(([K])=>K).sort(),[g]),A=l.useMemo(()=>u?oh(u):{},[u]),d=l.useMemo(()=>u?lh(u):{},[u]),j=l.useMemo(()=>u?Hl(ch(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"?Vs.positive:o==="mentionShare"?nr:nt[1],F=S?Xt.textDim:T,$=l.useMemo(()=>{const K=new Map(q.map(R=>[R.startDate,ah(R)]));return R=>K.get(String(R))??""},[q]),H=o==="mentionShare"?b?Jr(b.rows,Yt):null:q.length>0?ks(q[q.length-1][Cn(o)]*100):null,ve=o==="mentionShare"?b?Ch(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:jh,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(Aa,{options:vh,value:m,onChange:c,ariaLabel:"Series"}),e.jsx(Aa,{options:yh,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=bh(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(Th,{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=Jr(K,X),ae=uh(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:yo(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(Ih,{metric:o,mode:v,buckets:q})}),f.buckets.map(({bucketStartDate:X,events:Ae})=>e.jsx(gu,{x:X,stroke:Ah(Ae),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${X}`)),R.map((X,Ae)=>e.jsx(Fs,{type:"monotone",dataKey:X,name:X,stroke:yn(X,Ae),strokeDasharray:X===Yt?"5 4":void 0,strokeWidth:Sh(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:Nh},connectNulls:X!==Yt,isAnimationActive:!1},X))]})})}),e.jsx(Rh,{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 si=new Set([Nn.queued,Nn.running]);function Mh({projectName:t}){const s=Is(),[n,a]=l.useState(""),[r,o]=l.useState(""),[i,m]=l.useState(""),[c,h]=l.useState("__default__"),[p,u]=l.useState(null),y=Ie({...Wl({client:V,path:{name:t}}),staleTime:6e4}),v=Ie({...Yl({client:V}),staleTime:6e4}),b=Ie({...Xl({client:V,path:{name:t},query:{limit:20}}),refetchInterval:N=>N.state.data?.runs.some(T=>si.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({...Jl({client:V,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:f&&si.has(f.status)?3e3:!1}),O=C.data??null,E=l.useMemo(()=>Eh(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({...Zl(),onSuccess:async N=>{u(N.id),a(""),m(""),await Fh(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
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:qh(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:wo(N.status),children:N.status})})]},N.id))})]})})]})]}),e.jsx(Lh,{detail:O,isLoading:C.isFetching})]})}function Lh({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 ${Oh(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(oe,{tone:wo(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:Gh(o.status),children:o.status})}),e.jsx("td",{children:e.jsx(oe,{tone:o.answerMentioned===!0?"positive":o.answerMentioned===!1?"neutral":o.status===Us.failed?"negative":"caution",children:o.answerMentioned===null?o.status===Us.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===Us.failed?"negative":"caution",children:o.citationState===null?o.status===Us.failed?"Unavailable":"Pending":o.citationState==="cited"?"Cited":"Not cited"})})]},o.id))})]})}),e.jsx(Dh,{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 Dh({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===Us.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=qs(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(lu,{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 Eh(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 qh(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 Oh(t){return t.length>8?t.slice(0,8):t}function wo(t){return t===Nn.completed?"positive":t===Nn.partial?"caution":t===Nn.failed?"negative":"neutral"}function Gh(t){return t===Us.completed?"positive":t===Us.failed?"negative":"neutral"}async function Fh(t){await ft(t,"researchRuns")}const Ya=new Set(["queued","seeding","probing"]);function _h({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(Uh,{projectName:t}):e.jsx(Mh,{projectName:t})})]})}function Uh({projectName:t}){const s=Is(),[n,a]=l.useState(null),[r,o]=l.useState(""),[i,m]=l.useState("100"),c=Ie({...ec({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({...tc({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&Ya.has(p.status)?3e3:!1}),y=u.data??null,v=Ie({...sc({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),nc(t,d)},onSuccess:async d=>{a(d.sessionId),o(""),await ai(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 ac(t,n,d)},onSuccess:async d=>{await ai(s,t,d.sessionId),s.invalidateQueries({queryKey:Qi({client:V})}),s.invalidateQueries({predicate:j=>Array.isArray(j.queryKey)&&j.queryKey[0]==="projects"&&j.queryKey.length>1}),Se({title:"Queries added",detail:zh(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:ni(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:ni(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(Ji,{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:Bh(d.bucket),children:Kh(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 ni(t){return t==="completed"?"positive":t==="failed"?"negative":Ya.has(t)?"caution":"neutral"}function Bh(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Vh={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Kh(t){return t?Vh[t]:"Not classified"}function Pa(t){return t.length>8?t.slice(0,8):t}function zh(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 ai(t,s,n){await Promise.all([ft(t,"discovery"),t.invalidateQueries({queryKey:rc({client:V})})])}function ri(t){return`${(t*100).toFixed(1)}%`}function Qh({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),m=Ie({...ic({client:V,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=Ie({...oc({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({...lc({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(fu,{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:ri(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:ri(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 ii={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Hh={contract:null,assessment:null,googleAds:ii,gtm:ii,snapshots:[]};function Wh(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Zh(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Yh(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 Xh(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 Jh(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 So(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"&&ex(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 Zh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function ex(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Co(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 tx(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 sx(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 Ms(t){return t.length<=12?t:`…${t.slice(-10)}`}function nx(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 ax(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 oi(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 rx(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function ix(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 ox(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function li({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=Co(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 lx="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.",cx="Available once Google Ads and Tag Manager are connected.",dx="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 ux({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:Xh(t)},{title:"Tag Manager",state:t.gtm.state,ready:m,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?u:Jh(t)}],b=i&&m&&!p?So(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:dx}):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:lx})]}),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:cx})]}),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"}:Co(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 mx({workspace:t=Hh,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=Wh(t),b=Yh(v),g=So(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(ux,{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:[ox(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:nx(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:ax(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:Ms(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:Ms(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:Ms(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:Ms(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=oi(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=tx(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:sx(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:[li({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:p}:{},actionPending:n}),li({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:Ms(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=oi(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 ",rx(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:Ms(t.contract.gtm.tagId)})," fires with ",ix(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:Ms(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Ls=3e4,ci={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 di(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 hx(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 xx(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function px(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:xx(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 gx(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 ui(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 mi({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 hi({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 fx({projectId:t,projectName:s}){const n=Hi(),[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(ci),[ve,ue]=l.useState(null),z=l.useRef(null),ee=Ie({...cc({client:V,path:{name:s}}),staleTime:Ls}),re=Ie({...dc({client:V,path:{name:s}}),staleTime:Ls}),W=Ie({...uc({client:V,path:{name:s}}),staleTime:Ls}),K=Ie({...mc({client:V,path:{name:s}}),staleTime:Ls}),R=K.data,se=Ie({...hc({client:V,path:{name:s},query:{limit:5}}),staleTime:Ls}),ce=Ie({...xc({client:V,path:{name:s},query:{limit:5}}),staleTime:Ls}),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({...pc({client:V,path:{name:s,contractId:Ae?.id??""}}),enabled:!!Ae,staleTime:Ls}),Ne=Ie({...gc({client:V,path:{name:s}}),enabled:u==="google-ads"&&ee.data?.connected===!0,staleTime:0}),Le=Ie({...fc({client:V,path:{name:s}}),enabled:u==="gtm"&&re.data?.connected===!0,staleTime:0}),Fe=Ie({...bc({client:V,path:{name:s,accountId:d}}),enabled:u==="gtm"&&!!d,staleTime:0}),Pe=Ie({...yc({client:V,path:{name:s,accountId:d,containerId:S}}),enabled:u==="gtm"&&!!d&&!!S,staleTime:0}),Qe=qt(vc({client:V})),he=qt(jc({client:V})),we=qt(Nc({client:V})),Ze=qt(wc({client:V})),_e=qt(Sc({client:V})),He=qt(Cc({client:V})),Te=qt(kc({client:V})),Ce=qt(Ac({client:V})),G=qt(Pc({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:hx(ee.data,di(se.data?.total??0,se.isLoading,se.isError,se.error),ee.isError),gtm:px(re.data,di(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(Vi,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){Bi({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."),ui(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."),ui(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:gx($,w,{accountId:ie.accountId,containerId:ie.containerId})});H(ci),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(mx,{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(mi,{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(mi,{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(hi,{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(hi,{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 bx=6e4,yx=["7d","14d","30d"],ar="not available",vx='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%.',jx="No Google Ads snapshot stored yet",Nx="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.",wx="No closed days yet",Sx="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.",Cx={"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}),ko=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),kx=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function sn(t,s){return t===null||!Number.isFinite(t)?ar:s===null?kx.format(t/1e6):Tu(t,s)}function Ta(t){if(t===null||!Number.isFinite(t))return ar;const s=t*100;return s>0&&s<.1?"<0.1%":`${ko.format(s)}%`}function Ax(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%":`${ko.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function Px(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function Rx(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function Ix(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 Tx({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=Ie({...Rc({client:V,path:{name:t},query:{window:s}}),staleTime:bx}),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:vx})]}),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:yx,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?wx:jx}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:d?Sx:Nx})]})]})}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:Cx["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 ${Ix(d.change,d.direction)}`,children:Ax(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(eo,{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:Px(d.status),children:Rx(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,$x=50,Mx=50;function rr(t){return t==="viewer"}function ir(t){return t?.status==="unavailable"}function Ao(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Po(t,s){const n=new Map(s.map(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 Lx(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 xi(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function pi(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,$x),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(Ao(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 Dx({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
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:xi(S.status),children:pi(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:xi(S.status),children:pi(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 Ex="—";function qx({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,Mx),Ze=we.filter(L=>!Xa(L)),_e=[...new Set(re.split(`