@canonry/canonry 4.178.0 → 4.178.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +1 -1
- package/assets/assets/{AuditHistoryPanel-BmKdyRrR.js → AuditHistoryPanel-BCtMrEMF.js} +1 -1
- package/assets/assets/{BacklinksPage-DtqKPVLV.js → BacklinksPage-CIo2hA0i.js} +1 -1
- package/assets/assets/{HistoryPage-yyJsQiJQ.js → HistoryPage-D24U8cUG.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-hjW4iYtr.js → MeasurementPropertyPage-BKDdv-jJ.js} +1 -1
- package/assets/assets/{ProjectPage-DZKpnPvq.js → ProjectPage-DrIs_ZuR.js} +1 -1
- package/assets/assets/{RunRow-BZeBFb22.js → RunRow-B39IK7hK.js} +1 -1
- package/assets/assets/{RunsPage-tnXHsK_R.js → RunsPage-R4W1kD0B.js} +1 -1
- package/assets/assets/{SettingsPage-Djj5k8vv.js → SettingsPage-BAOGyt1F.js} +1 -1
- package/assets/assets/{SiteHealthSection-BkDncS11.js → SiteHealthSection-Bx7yVNMQ.js} +3 -3
- package/assets/assets/{TrafficPage-nJggXVh-.js → TrafficPage-DL8RvM2R.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-zxONbSn-.js → TrafficSourceDetailPage-COzjakZa.js} +1 -1
- package/assets/assets/{extract-error-message-NpQu2vBm.js → extract-error-message-B3TERCQ-.js} +1 -1
- package/assets/assets/index-xtxQtZRo.js +83 -0
- package/assets/assets/{react-sigma_core.esm.min-CxMdd8U8.js → react-sigma_core.esm.min-CbXAujub.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-YIQMTOEZ.js → chunk-5KI5WVWS.js} +86 -7
- package/dist/{chunk-A7FB2BVW.js → chunk-EAUE2RRY.js} +2 -2
- package/dist/{chunk-O7J5WFVZ.js → chunk-LMI72WZP.js} +101 -41
- package/dist/{chunk-T4JH77O6.js → chunk-OYDIND7Q.js} +71 -1
- package/dist/{chunk-SXKA4OXZ.js → chunk-P6JVZJO5.js} +3 -3
- package/dist/cli.js +6 -6
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-YISV327N.js → intelligence-service-KYIQZBEO.js} +2 -2
- package/dist/mcp.js +3 -3
- package/package.json +11 -11
- package/assets/assets/index-Dwwnkd_V.js +0 -83
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as l,j as e,L as as,n as Cs,u as Ie,o as Et,B as yr,C as Eo,h as qo,k as Oo,D as Go}from"./vendor-tanstack-Dock0eH1.js";import{M as jr,I as Je,T as oe,t as Fo,a as _o,u as Nr,C as Uo,P as Js,B as P,h as Bo,b as Vo,c as Ko,d as pe,i as J,e as ft,f as Me,g as an,j as zo,k as U,l as Qo,m as Ho,n as Wo,o as Yo,p as wr,q as Xo,r as Jo,S as Ls,s as Zo,v as el,w as Ts,x as qt,y as tl,z as hi,A as Sr,G as $t,D as Ba,E as sl,F as nl,H as al,J as il,K as xi,L as Se,N as rl,O as ol,Q as oa,R as ll,U as cl,V as dl,W as ul,X as ml,Y as hl,Z as xl,_ as pl,$ as gl,a0 as fl,a1 as bl,a2 as vl,a3 as yl,a4 as jl,a5 as Nl,a6 as Cr,a7 as Os,a8 as wl,a9 as kr,aa as Kn,ab as Sl,ac as Ye,ad as Cl,ae as kl,af as Al,ag as zn,ah as Pl,ai as Rl,aj as Il,ak as Zs,al as $l,am as Tl,an as Ml,ao as Ar,ap as Ta,aq as Ll,ar as Pr,as as Dl,at as Va,au as El,av as ql,aw as Ol,ax as Gl,ay as Fl,az as _l,aA as Ul,aB as hn,aC as Ds,aD as Bl,aE as Vl,aF as Kl,aG as zl,aH as Rr,aI as Ql,aJ as Hl,aK as Wl,aL as Yl,aM as Xl,aN as Ir,aO as Jl,aP as Zl,aQ as ec,aR as tc,aS as sc,aT as nc,aU as ac,aV as ic,aW as rc,aX as oc,aY as lc,aZ as cc,a_ as dc,a$ as uc,b0 as mc,b1 as hc,b2 as xc,b3 as pc,b4 as gc,b5 as fc,b6 as ts,b7 as bc,b8 as it,b9 as vc,ba as yc,bb as jc,bc as Nc,bd as wc,be as Sc,bf as Cc,bg as kc,bh as Ac,bi as Pc,bj as Rc,bk as Ic,bl as $c,bm as Tc,bn as Mc,bo as Lc,bp as Dc,bq as Ec,br as qc,bs as Oc,bt as Gc,bu as Fc,bv as _c,bw as Uc,bx as Bc,by as Vc,bz as Kc,bA as zc,bB as Qc,bC as Hc,bD as Wc,bE as Yc,bF as Xc,bG as Jc,bH as Zc,bI as ed,bJ as td,bK as sd,bL as la,bM as nd,bN as ad,bO as pi,bP as id,bQ as rd,bR as od,bS as ld,bT as cd,bU as dd,bV as ud,bW as md,bX as hd,bY as xd,bZ as pd,b_ as gd,b$ as $r,c0 as fd,c1 as bd,c2 as vd,c3 as yd,c4 as jd,c5 as Nd,c6 as wd,c7 as gi,c8 as Sd,c9 as ca,ca as Cd,cb as kd,cc as Ad,cd as Pd,ce as Rd,cf as Id,cg as $d,ch as Tr,ci as Td,cj as Md,ck as Ld,cl as Dd,cm as Ed,cn as qd,co as Pn,cp as Od,cq as Gd,cr as Fd,cs as fi,ct as _d}from"./index-Dwwnkd_V.js";import{R as Ud}from"./RunRow-BZeBFb22.js";import{u as pn,D as Hs,a as Es,b as Mr,M as Un,c as os,S as Bd}from"./SiteHealthSection-BkDncS11.js";import{e as Vd,q as Qn,U as Kd,r as zd,L as Qd,s as Lr,i as Hd,P as Hn,D as Dr,t as Wd,u as Yd,E as Xd,C as Wn,v as Jd}from"./vendor-lucide-nYKv-BB7.js";import{f as gn,C as Gs,a as ns,b as Ut,c as Ws,d as Ht,e as rt,g as qs,M as Er,h as qr,i as Or,o as us,j as Ss,p as Zd}from"./ChartPrimitives-B_LDVvTy.js";import{u as eu,t as tu,e as su,a as ut}from"./extract-error-message-NpQu2vBm.js";import{R as fn,C as bn,X as vn,Y as yn,T as jn,L as Gr,A as zs,a as Fr,b as nu,d as _r,e as au}from"./vendor-recharts-D8rt5lKn.js";import{A as iu}from"./AuditHistoryPanel-BmKdyRrR.js";import{a as ru,b as ou}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function Bn(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function lu(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let i=t;i<=s&&(a.push(i),!(a.length>=n));i=cu(i,1));return a}function cu(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const i=a.getUTCFullYear(),r=String(a.getUTCMonth()+1).padStart(2,"0"),o=String(a.getUTCDate()).padStart(2,"0");return`${i}-${r}-${o}`}function du(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function uu(t,s){const n=du(t,s);return n===null?null:Math.round(n*100)}function da(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Bn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Bn(t.prior)} ${s})`:`Flat ${n} (${Bn(t.prior)} ${s})`}const Ur=30;function bi(t){return Math.round(t*10)/10}function mu(t){return t.prior>=Ur&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${bi(t.deltaAbs)} vs ${bi(t.prior)}`}function hu(t,s,n){return t.prior>=Ur&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Bn(Math.round(t.deltaAbs))} ${s} ${n}`}const xu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Br(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Vr(t){return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function Kr(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Br).map(Vr).filter(Boolean)):new Set}function zr(t,s){const n=Br(t).map(Vr).filter(Boolean).filter(a=>!xu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function pu(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function gu(t,s){const n=Kr(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const o=zr(pu(r),n);!o||a.has(o)||(a.add(o),i.push(r))}return i}function fu(t){const s=Kr(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=zr(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}const bu=1e6;function vu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/bu)}const Qr={queryClass:"all"},yu=["all","non-brand","branded"];function ju(t){return typeof t=="string"&&yu.includes(t)}function Nu(t){const s=ju(t.class)?t.class:Qr.queryClass,n=t.scope;if(typeof n!="string"||n==="all"||n.length===0)return{scope:"all",queryClass:s};const a=n.startsWith("group:")?n.slice(6):"";return a?{scope:"group",groupKey:a,queryClass:s}:{scope:"all",queryClass:s}}function wu(t,s){return s===null||t===null?!1:t!==s}function Su(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===Qr.queryClass?void 0:t.queryClass}}const As=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],vi={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Cu={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},ku="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Au(t,s){if(s.unavailable)return{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1};if(s.noRun)return{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1};if(t.snapshotsTotal===0)return s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1};if(t.snapshotsWithAnswerText===0)return{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1};if(!s.hasCompetitors)return{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1};const n=t.projectMentionSnapshots+t.competitorMentionSnapshots;return n===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:`${t.score}`,numeric:!0,detail:`${t.projectMentionSnapshots} of ${n} brand mentions`,showRows:!0}}function Pu({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const i=new Map(t.perCompetitor.map(o=>[o.domain,o.mentionSnapshots])),r=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(o=>({label:o,mentions:i.get(o)??0,isYou:!1}))].sort((o,m)=>m.mentions-o.mentions||(o.label<m.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Je,{text:ku})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:r.map(o=>{const m=o.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${o.isYou?"text-heading font-medium":"text-secondary"}`,children:o.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${o.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${m>0?Math.max(m,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:o.mentions}),e.jsxs("td",{className:"mention-share-share",children:[m.toFixed(1),"%"]})]},o.label)})})]})}function Ru({summary:t,projectLabel:s,competitorDomains:n}){const[a,i]=l.useState("non-brand"),r=l.useId(),o=t.scope==="pooled",m=!o&&t.branded.snapshotsTotal>0,c=m?a:"non-brand",h=o?"pooled":c,p=c==="branded"?t.branded:t.breakdown,u=c==="branded"?t.breakdown:t.branded,v=Au(p,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:u.snapshotsTotal>0}),j=h==="non-brand"?jr[t.tone]:"text-secondary";function b(g){const f=As.findIndex(O=>O.value===c);let k=null;g.key==="ArrowRight"||g.key==="ArrowDown"?k=(f+1)%As.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?k=(f-1+As.length)%As.length:g.key==="Home"?k=0:g.key==="End"&&(k=As.length-1),k!==null&&(g.preventDefault(),i(As[k].value),g.currentTarget.querySelectorAll('[role="radio"]')[k]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:r,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Je,{text:Cu[h]})]}),m?e.jsx("div",{role:"radiogroup","aria-labelledby":r,className:"segmented flex-wrap",onKeyDown:b,children:As.map(g=>{const f=g.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>i(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:vi[h]})]}),v.numeric?e.jsxs("p",{className:`mention-share-value ${j}`,children:[v.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:v.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:vi[h]}),` · ${v.detail}`]}),o&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),v.showRows&&e.jsx(Pu,{breakdown:p,projectLabel:s,competitorDomains:n})]})}function Ma({state:t,label:s}){return e.jsx(oe,{tone:_o(t),children:s??Fo(t)})}function yi({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},i={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((h,p)=>{const u=new Date(h.createdAt).toLocaleDateString();return`${p===r?"Latest run, ":""}${u}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:o}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,p)=>{const u=!!(h.model&&p>0&&n[p-1]?.model&&n[p-1].model!==h.model),v=p===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${u?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${v?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,u?"model changed":null,v?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[m," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function La(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Iu=320;function $u(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function ji(t,s){return s==="citations"?t.citationState:t.visibilityState==="pending"||t.answerMentioned==null&&t.visibilityState==null?"pending":t.visibilityState==="visible"||t.answerMentioned===!0?"cited":"not-cited"}function Ni(t,s){if(s==="mentions")switch(t){case"cited":return"Mentioned";case"not-cited":return"Not Mentioned";case"pending":return"Pending";case"emerging":return"Newly Mentioned";case"lost":return"No Longer Mentioned"}switch(t){case"cited":return"Cited";case"not-cited":return"Not Cited";case"lost":return"Lost";case"emerging":return"Emerging";case"pending":return"Pending"}}function wi(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let o=0;for(let m=t.length-1;m>=0&&t[m].citationState===i;m--)o++;return i==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Tu(t,s){return t.map(n=>Hr(n,s))}function Hr(t,s){return s==="citations"?t:{...t,citationState:ji(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:ji(n,s)}))}}function Si(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",m=r==="cited"||r==="emerging";return i==="lost"||r!==null&&m&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!m&&o?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Mu(t){const s=La(Tu(t,"mentions")),n=La(t);return[Si(s,"mentions"),Si(n,"citations")]}function Lu({signal:t}){const s=t.tone==="positive"?"border-positive-500/25 bg-positive-500/10 text-positive":t.tone==="negative"?"border-negative-500/25 bg-negative-500/10 text-negative":t.tone==="pending"?"border-caution-500/20 bg-caution-500/10 text-caution":"border-mono-700/60 bg-bg-elevated/70 text-secondary";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function Ci({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Mu(t).map(s=>e.jsx(Lu,{signal:s},s.key))})}function Du({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Nr(),[i,r]=l.useState(new Set),[o,m]=l.useState("mentions"),[c,h]=l.useState(n),p=l.useMemo(()=>{const O=new Map;for(const q of t){const A=q.query,d=s?q.location??null:null,y=s?JSON.stringify([A,d]):A,S=O.get(y)??{key:y,phrase:A,location:d,items:[],rawItems:[]};S.items.push(Hr(q,o)),S.rawItems.push(q),O.set(y,S)}return[...O.values()]},[t,o,s]),u=pn({rows:p,getSearchText:$u}),v=u.rows.map(O=>O.key),j=v.length>0&&v.every(O=>i.has(O)),b=O=>{r(q=>{const A=new Set(q);return A.has(O)?A.delete(O):A.add(O),A})},g=o==="mentions"?"mentioned":"cited",f=o==="mentions"?"Mention History":"Citation History",k=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(O=>{const q=new Set(O);for(const A of v)j?q.delete(A):q.add(A);return q})},children:j?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),p.length>0?e.jsx(Hs,{value:u.query,onChange:u.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:f}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:u.rows.map(({key:O,phrase:q,location:A,items:d,rawItems:y})=>{const S=i.has(O),V=d.map($=>$.citationState),K=V.includes("cited")?"cited":V.includes("emerging")?"emerging":V.includes("lost")?"lost":V.every($=>$==="pending")?"pending":"not-cited",w=La(d),T=d.filter($=>$.citationState===Uo.cited||$.citationState==="emerging").length,F=wi(w,o);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>b(O),onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),b(O))},tabIndex:0,role:"button","aria-expanded":S,children:[e.jsx("td",{children:e.jsx(Vd,{size:14,className:`transition-transform duration-150 text-muted ${S?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:q}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:A??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:d.map($=>e.jsx(Js,{provider:$.provider},$.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{state:K,label:Ni(K,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${T} of ${d.length} engines ${k}`,children:[T,"/",d.length]})]})}),e.jsx("td",{children:e.jsx(yi,{history:w})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:F}),e.jsx(Ci,{items:y})]}),e.jsx("td",{})]}),S&&d.map(($,H)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Js,{provider:$.provider})}),e.jsx("td",{children:e.jsx(Ma,{state:$.citationState,label:Ni($.citationState,o)})}),e.jsx("td",{children:e.jsx(yi,{history:$.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:wi($.runHistory,o)}),e.jsx(Ci,{items:[y[H]??$]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:ye=>{ye.stopPropagation(),a($.id)},children:"View"})})]}),c==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Ou,{item:$,onViewFull:()=>a($.id)})})]})]},$.id))]},O)})})]})}),u.totalRows===0&&u.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Es,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",g==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Eu(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(i=>{const r=Vo(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function ki(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function qu(t,s){if(t.length<=s)return{body:t,truncated:!1};const n=t.lastIndexOf(" ",s);return{body:`${t.slice(0,n>s-40?n:s).trimEnd()}…`,truncated:!0}}function Ou({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:i}=qu(t.answerSnippet,Iu),r=Eu(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:Bo(a,r)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${ki(t,o)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[o,ki(t,o)?" · competitor source":""]},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Gu({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const m=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),c=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:c,onClick:i?()=>s(o.domain):void 0,title:i?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:Ko(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:h=>{h.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Rn({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}const Fu=6,en="__other__",Ys="_socialTotal";function _u(t,s=Fu){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const a=[...n.entries()].sort((p,u)=>u[1]!==p[1]?u[1]-p[1]:p[0].localeCompare(u[0])),i=a.slice(0,s),r=new Set(i.map(([p])=>p)),o=Math.max(0,a.length-s),m=new Map;for(const p of t){let u=m.get(p.date);u||(u={date:p.date,[Ys]:0},m.set(p.date,u));const v=r.has(p.source)?p.source:en;u[v]=(u[v]??0)+p.sessions,u[Ys]=(u[Ys]??0)+p.sessions}const c=[...m.values()].sort((p,u)=>String(p.date).localeCompare(String(u.date))),h=i.map(([p])=>p);return o>0&&h.push(en),{data:c,sources:h,otherCount:o}}function Xs(t){return t.replace(/\+/g," ")}function Wr(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ai="_totalSessions",Pi="_organicSessions";function Uu(t,s){const n=new Map;for(const o of s)n.set(o.date,{[Ai]:o.sessions,[Pi]:o.organicSessions});for(const o of t.days){let m=n.get(o.date);m||(m={[Ai]:0,[Pi]:0},n.set(o.date,m));for(const c of o.bySource)m[c.source]=(m[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([o],[m])=>o.localeCompare(m)).map(([o,m])=>({date:o,...m})),i=a.map(o=>o.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const Bu=["7d","30d","90d","all"],js=rt,Da=Ht.textDim,Yr=Ht.textFaint,rn=25;function Vu(t){return Mr(t.landingPage)}const Ku=25,zu=10,ua={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function In(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Xr(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Qu({projectName:t}){const{data:s,isLoading:n,isError:a}=eu(t);if(n)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!J()&&e.jsx(as,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(pe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!J()&&e.jsxs(e.Fragment,{children:[e.jsx(as,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(pe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:tu(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Xr(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:J()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(as,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function Hu({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Qu,{projectName:t}),e.jsx(Wu,{projectName:t})]})}function Wu({projectName:t}){const s=Cs(),[n,a]=l.useState(null),[i,r]=l.useState(null),[o,m]=l.useState(!0),[c,h]=l.useState(!1),[p,u]=l.useState(!1),[v,j]=l.useState(null),[b,g]=l.useState(null),[f,k]=l.useState("sessions"),[O,q]=l.useState("desc"),[A,d]=l.useState("sessions"),[y,S]=l.useState("desc"),[V,K]=l.useState("sessions"),[w,T]=l.useState("desc"),[F,$]=l.useState("sessions"),[H,ye]=l.useState("desc"),[ge,z]=l.useState(ua),[ee,ie]=l.useState([]),[W,B]=l.useState([]),[R,se]=l.useState(!1),[le,de]=l.useState("30d");async function X(G){m(!0),j(null);try{const ke=await s.fetchQuery({...zo({client:U,path:{name:t}}),staleTime:an});if(G.current)return;if(a(ke),!ke.connected){r(null),z(ua),ie([]),B([]),m(!1);return}const fe=le==="all"?void 0:le,he=await s.fetchQuery({...Qo({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).then(Wt=>Wt),Mt=he.windowStart||he.windowEnd?{...he.windowStart?{startDate:he.windowStart}:{},...he.windowEnd?{endDate:he.windowEnd}:{}}:void 0,[ct,Pt,Lt]=await Promise.all([s.fetchQuery({...Ho({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).catch(()=>ua),s.fetchQuery({...Wo({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).catch(()=>[]),s.fetchQuery({...Yo({client:U,path:{name:t},query:Mt}),staleTime:an}).catch(()=>[])]);if(G.current)return;r(he),z(ct),ie(Pt),B(Lt),m(!1)}catch(ke){if(G.current)return;j(ke instanceof Error?ke.message:"Failed to load GA4 data"),m(!1)}}l.useEffect(()=>{const G={current:!1};return X(G),()=>{G.current=!0}},[t,le,s]);async function Ae(){h(!0),j(null),g(null);try{const G=await wr(t);g(`Synced ${G.rowCount.toLocaleString()} page rows, ${G.aiReferralCount.toLocaleString()} AI and ${G.socialReferralCount.toLocaleString()} social referral rows (${G.days} days)`),await ft(s,"ga"),await X({current:!1})}catch(G){j(G instanceof Error?G.message:"Sync failed")}finally{h(!1)}}async function _(){u(!0),j(null),g(null);try{await Xo(t),await ft(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),g("GA4 disconnected")}catch(G){j(G instanceof Error?G.message:"Disconnect failed")}finally{u(!1)}}function ae(G){Pe.setPage(1),f===G?q(ke=>ke==="desc"?"asc":"desc"):(k(G),q("desc"))}function Ne(G){A===G?S(ke=>ke==="desc"?"asc":"desc"):(d(G),S("desc"))}function Le(G){V===G?T(ke=>ke==="desc"?"asc":"desc"):(K(G),T("desc"))}const Fe=l.useMemo(()=>i?.topPages?[...i.topPages].sort((G,ke)=>{const fe=G[f],he=ke[f];return typeof fe=="string"&&typeof he=="string"?O==="asc"?fe.localeCompare(he):he.localeCompare(fe):O==="asc"?fe-he:he-fe}):[],[i?.topPages,f,O]),Pe=pn({rows:Fe,getSearchText:G=>Mr(G.landingPage),pageSize:zu}),Qe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((G,ke)=>{const fe=G[A],he=ke[A];return typeof fe=="string"&&typeof he=="string"?y==="asc"?fe.localeCompare(he):he.localeCompare(fe):y==="asc"?fe-he:he-fe}):[],[i?.aiReferrals,A,y]),ue=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((G,ke)=>{const fe=G[F],he=ke[F];return typeof fe=="string"&&typeof he=="string"?H==="asc"?fe.localeCompare(he):he.localeCompare(fe):H==="asc"?fe-he:he-fe}):[],[i?.aiReferralLandingPages,F,H]),we=pn({rows:ue,getSearchText:Vu,pageSize:Ku}),Ze=we.totalRows>0?`${we.totalRows.toLocaleString()} ${we.hasQuery?we.totalRows===1?"match":"matches":we.totalRows===1?"row":"rows"}`:we.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function _e(G){we.setPage(1),F===G?ye(ke=>ke==="desc"?"asc":"desc"):($(G),ye("desc"))}const He=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((G,ke)=>{const fe=G[V],he=ke[V];return typeof fe=="string"&&typeof he=="string"?w==="asc"?fe.localeCompare(he):he.localeCompare(fe):w==="asc"?fe-he:he-fe}):[],[i?.socialReferrals,V,w]),{socialChartData:$e,socialChartSources:Ce,socialOtherCount:E}=l.useMemo(()=>{const G=_u(W);return{socialChartData:G.data,socialChartSources:G.sources,socialOtherCount:G.otherCount}},[W]),{chartData:M,chartSources:L,dateRange:je}=l.useMemo(()=>{const G=Uu(ge,ee);return{chartData:G.data,chartSources:G.sources,dateRange:G.dateRange}},[ge,ee]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return J()?e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Yu,{projectName:t,onConnected:()=>{(async()=>(await ft(s,"ga"),await X({current:!1})))()}});const qe=i?.organicSharePctDisplay??"0%",Y=i?.channelBreakdown?.organic.sharePctDisplay??qe,Be=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,mt=i?.aiSessionsDeduped??0,ot=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,De=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Oe=i?.paidAiSessionsBySession??0,xt=i?.paidAiSharePctBySessionDisplay??"0%",We=i?new Set(i.aiReferrals.map(G=>G.source.toLowerCase())).size:0,Ve=Qe[0]??null,Te=i?.totalDirectSessions??0,jt=i?.directSharePctDisplay??"0%",Tt=i?.channelBreakdown?.direct.sessions??Te,Ue=i?.channelBreakdown?.direct.sharePctDisplay??jt,Ge=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,bt=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ke=i?.socialSessions??0,Nt=i?.socialSharePctDisplay??"0%",kt=i?.channelBreakdown?.social.sessions??Ke,vt=i?.channelBreakdown?.social.sharePctDisplay??Nt,At=i?new Set(i.socialReferrals.map(G=>G.source.toLowerCase())).size:0,lt=He[0]??null;return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:v}),b&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:b}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!J()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:c,onClick:Me(Ae),children:[e.jsx(Qn,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),c?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:p,onClick:Me(_),children:[e.jsx(Kd,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Je,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:Bu.map(G=>e.jsx("button",{type:"button","aria-pressed":le===G,className:`segmented-option ${le===G?"segmented-option-active":""}`,onClick:()=>de(G),children:G==="all"?"All":G},G))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(ma,{value:In(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(ma,{value:In(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${qe} of total`,tone:"positive"}),e.jsx(ma,{value:i.totalUsers===null?"—":In(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!J()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:c,onClick:Me(Ae),children:[e.jsx(Qn,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Je,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),je&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(je.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(je.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),M.length>0&&e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:L.length>0?"AI vs. total sessions":"All sessions (baseline)"}),L.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),L.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:M,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(G,ke)=>{const fe=typeof G=="number"?G.toLocaleString():String(G??0),he=String(ke??"");return he==="_totalSessions"?[fe,"Total Sessions"]:he==="_organicSessions"?[fe,"Organic Sessions"]:[fe,he]}}),e.jsx(Gr,{wrapperStyle:{fontSize:11,color:Ht.text},formatter:G=>G==="_totalSessions"?"Total Sessions":G==="_organicSessions"?"Organic Sessions":G}),e.jsx(zs,{type:"monotone",dataKey:"_totalSessions",stroke:Ht.textFaint,fill:Ht.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),L.map((G,ke)=>e.jsx(zs,{type:"monotone",dataKey:G,stackId:"ai",stroke:js[ke%js.length],fill:js[ke%js.length],fillOpacity:.4,strokeWidth:1.5},G))]})})})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Jt,{label:"Organic",value:Y,hint:`${Be.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(Jt,{label:"Social",value:vt,hint:`${kt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(Jt,{label:"Direct",value:Ue,hint:`${Tt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(Jt,{label:"Visitors from AI (at least)",value:De,hint:Oe>0?`${ot.toLocaleString()} sessions · ${Oe.toLocaleString()} paid`:`${ot.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(Jt,{label:"Other channels",value:bt,hint:`${Ge.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),Ve&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:Ve.source})," via ",Ve.medium,", accounting for ",Ve.sessions.toLocaleString()," sessions.",Oe>0&&e.jsxs("span",{children:[" Paid AI: ",Oe.toLocaleString()," sessions (",xt,")."]})]})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${We} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Source",sortKey:"source",current:A,dir:y,onSort:Ne,align:"left"}),e.jsx(_t,{label:"Medium",sortKey:"medium",current:A,dir:y,onSort:Ne,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:A,dir:y,onSort:Ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Qe.map(G=>e.jsx(Ju,{referral:G,totalSessions:mt},`${G.source}:${G.medium}:${G.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:Ze})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:we.query,onChange:we.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),we.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Landing Page",sortKey:"landingPage",current:F,dir:H,onSort:_e,align:"left"}),e.jsx(_t,{label:"Source",sortKey:"source",current:F,dir:H,onSort:_e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:F,dir:H,onSort:_e,align:"right"})]})}),e.jsx("tbody",{children:we.rows.map(G=>e.jsx(Zu,{row:G},`${G.landingPage}:${G.source}:${G.medium}:${G.sourceDimension}`))})]})}),e.jsx(Es,{page:we.page,pageSize:we.pageSize,visibleRows:we.rows.length,totalRows:we.totalRows,onPageChange:we.setPage,itemLabel:we.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>we.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Je,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),$e.length>0&&e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),E>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ce.length-1," sources · ",E," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:$e,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(G,ke)=>{const fe=typeof G=="number"?G.toLocaleString():String(G??0),he=String(ke??"");if(he===Ys)return[fe,"Total Social"];if(he===en){const Mt=`Other (${E} source${E===1?"":"s"})`;return[fe,Mt]}return[fe,Xs(he)]}}),e.jsx(zs,{type:"monotone",dataKey:Ys,stroke:Yr,fill:Ht.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ce.map((G,ke)=>{const he=G===en?Da:js[ke%js.length];return e.jsx(zs,{type:"monotone",dataKey:G,stackId:"social",stroke:he,fill:he,fillOpacity:.4,strokeWidth:1.5},G)})]})})}),e.jsx(tm,{sources:Ce,otherCount:E})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Jt,{label:"Social Sessions",value:In(Ke),hint:`${Ke.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Jt,{label:"Share of Traffic",value:Nt,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Jt,{label:"Platforms",value:String(At),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),lt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${lt.source} via ${lt.medium}`,children:Wr(Xs(lt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:lt.medium,children:["via ",Xs(lt.medium)," · ",lt.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Jt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Jt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Jt,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?He.length>rn&&!R?`Top ${rn} of ${He.length}`:`${He.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Source",sortKey:"source",current:V,dir:w,onSort:Le,align:"left"}),e.jsx(_t,{label:"Medium",sortKey:"medium",current:V,dir:w,onSort:Le,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:V,dir:w,onSort:Le,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(_t,{label:"Users",sortKey:"users",current:V,dir:w,onSort:Le,align:"right"})]})}),e.jsx("tbody",{children:(R?He:He.slice(0,rn)).map(G=>e.jsx(em,{referral:G,totalSessions:Ke},`${G.source}:${G.medium}:${G.channelGroup}`))})]})}),He.length>rn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>se(G=>!G),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:R?`Show top ${rn}`:`Show all ${He.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Je,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Hs,{value:Pe.query,onChange:Pe.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Landing Page",sortKey:"landingPage",current:f,dir:O,onSort:ae,align:"left"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:f,dir:O,onSort:ae,align:"right"}),e.jsx(_t,{label:"Organic",sortKey:"organicSessions",current:f,dir:O,onSort:ae,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Pe.rows.map(G=>e.jsx(Xu,{page:G},G.landingPage))})]})}),Pe.totalRows===0&&Pe.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Es,{page:Pe.page,pageSize:Pe.pageSize,visibleRows:Pe.rows.length,totalRows:Pe.totalRows,onPageChange:Pe.setPage,itemLabel:Pe.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Xr(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Yu({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[i,r]=l.useState(null),[o,m]=l.useState(null),[c,h]=l.useState(!1),[p,u]=l.useState(null),v=l.useRef(null),j=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),r(f.name);const k=new FileReader;k.onload=()=>{const O=k.result;try{const q=JSON.parse(O);if(!q.client_email||!q.private_key){u("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),m(null);return}m(O)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},k.onerror=()=>{u("Failed to read file."),m(null)},k.readAsText(f)},[]);async function b(){if(u(null),!n.trim()){u("Property ID is required.");return}if(!o){u("Please upload a service account key file.");return}h(!0);try{await Jo(t,{propertyId:n.trim(),keyJson:o});try{await wr(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(pe,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),p&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:p}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:g=>a(g.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:v,type:"file",accept:".json,application/json",onChange:j,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>v.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(zd,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(P,{variant:"default",size:"sm",disabled:c||!n.trim()||!o,onClick:Me(b),children:c?"Connecting & syncing…":"Connect GA4"})]})}function _t({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const o=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Jr={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function ma({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${Jr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Jt({value:t,label:s,hint:n,tone:a,tooltip:i}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,i&&e.jsx(Je,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Jr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Xu({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]})]})}const Zr={session:"Session",first_user:"First Visit",manual_utm:"UTM"},eo={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function Ju({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Zr[t.sourceDimension]??t.sourceDimension,i=eo[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Zu({row:t}){const s=Zr[t.sourceDimension]??t.sourceDimension,n=eo[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(Un,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function em({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Xs(t.source),r=Xs(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function tm({sources:t,otherCount:s}){const n=[{key:Ys,color:Yr,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===en)n.push({key:en,color:Da,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Xs(i);n.push({key:i,color:js[a%js.length]??Da,label:Wr(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function to({windows:t,value:s,onChange:n,label:a,formatOption:i,disabled:r=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(o=>e.jsx("button",{type:"button","aria-pressed":s===o,disabled:r,className:`segmented-option ${s===o?"segmented-option-active":""}`,onClick:()=>n(o),children:i?i(o):o},o))})}function sm(t){const s=t.details;if(t.code!=="FORBIDDEN"||!s||s.reason!=="gsc-api-disabled")return null;const n=typeof s.projectNumber=="string"?s.projectNumber:void 0;return{title:"Enable the Search Console API",message:`Your Google Cloud project${n?` (${n})`:""} hasn't enabled the Search Console API. Enable the Search Console API and the Indexing API, wait ~2–5 minutes, then retry.`,enableUrl:typeof s.enableUrl=="string"?s.enableUrl:void 0,indexingApiUrl:typeof s.indexingApiUrl=="string"?s.indexingApiUrl:void 0,projectNumber:n}}const nm=["7d","30d","90d","all"],$n=500,Ri=[{key:"clicks",label:"Clicks",color:rt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:rt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:qs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:rt[2],inverted:!0,format:t=>t.toFixed(1)}],bs=25,am="canonry:google-oauth-complete",im=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function rm(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const i=t.change[s];if(i===null||!Number.isFinite(i)){const c=t.prior[s],h=t.trailing[s];return c!==null&&h!==null&&c<=0&&h>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(i===0)return`→ no change vs prior ${a}d`;const r=Math.abs(i*100),o=r<.1?"<0.1%":`${im.format(r)}%`;return`${(n?i<0:i>0)?"↑":"↓"} ${o} vs prior ${a}d`}function Ii(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function $i(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function Ti(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function om({projectName:t,refreshNonce:s}){const n=Cs(),[a,i]=l.useState(!1),[r,o]=l.useState([]),[m,c]=l.useState([]),[h,p]=l.useState([]),[u,v]=l.useState(null),[j,b]=l.useState([]),[g,f]=l.useState([]),[k,O]=l.useState(null),[q,A]=l.useState(""),[d,y]=l.useState(""),[S,V]=l.useState("30"),[K,w]=l.useState(!1),[T,F]=l.useState("30d"),[$,H]=l.useState(["clicks","impressions"]),[ye,ge]=l.useState(!0),[z,ee]=l.useState(null),[ie,W]=l.useState(0),[B,R]=l.useState({startDate:"",endDate:"",query:"",page:""}),[se,le]=l.useState(0),[de,X]=l.useState(!1),[Ae,_]=l.useState(0),[ae,Ne]=l.useState(!1),[Le,Fe]=l.useState(""),[Pe,Qe]=l.useState(!0),[ue,we]=l.useState(!1),[Ze,_e]=l.useState(!1),[He,$e]=l.useState(!1),[Ce,E]=l.useState(!1),[M,L]=l.useState(!1),[je,qe]=l.useState(!1),[Y,Be]=l.useState(null),[mt,ot]=l.useState(!1),[De,Oe]=l.useState(!1),[xt,We]=l.useState(null),[Ve,Te]=l.useState(null),[jt,Tt]=l.useState([]),[Ue,Ge]=l.useState(new Set),[bt,Ke]=l.useState({}),[Nt,kt]=l.useState(new Set),[vt,At]=l.useState(""),[lt,G]=l.useState(null),[ke,fe]=l.useState(""),[he,Mt]=l.useState(!1),[ct,Pt]=l.useState(!1),[Lt,Wt]=l.useState(!1),[Dt,is]=l.useState(!1),[nt,ms]=l.useState("indexed"),[wt,hs]=l.useState(null),Ot=!!(B.query.trim()||B.page.trim()||wt),Yt=wt!==null,Bt=l.useMemo(()=>{if(!wt)return h;const{key:x,dir:D}=wt;return[...h].sort((Z,ce)=>{const ze=x===Ls.CTR?Number.isFinite(Z.ctr)?Z.ctr:0:Z[x],Xe=x===Ls.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[x];return D==="asc"?ze-Xe:Xe-ze})},[h,wt]),et=pn({rows:Bt,pageSize:os}),xs=ae?et.rows:Bt,Gt=pn({rows:(xt??[]).filter(x=>x.path.toLowerCase().includes(vt.trim().toLowerCase())),pageSize:os}),[St,ps]=l.useState([]),[dt,Zt]=l.useState(null),[C,be]=l.useState(1),ve=l.useMemo(()=>{if(St.length<2)return null;const x=St[St.length-1],D=St[St.length-2];return{indexed:x.indexed-D.indexed,notIndexed:x.notIndexed-D.notIndexed}},[St]);l.useEffect(()=>{be(1)},[Y,nt,dt]);const I=l.useMemo(()=>dt?(Y?.reasonGroups??[]).find(x=>x.reason===dt):void 0,[Y,dt]),Q=l.useMemo(()=>Y?nt==="indexed"?Y.indexed:nt==="deindexed"?Y.deindexed:nt==="notIndexed"?dt?I?.urls??[]:(Y.reasonGroups??[]).length===0?Y.notIndexed:[]:[]:[],[Y,nt,dt,I]),me=Math.max(1,Math.ceil(Q.length/bs)),te=Math.min(Math.max(1,C),me),ne=(te-1)*bs,Ee=l.useMemo(()=>Y?.indexed.slice(ne,ne+bs)??[],[Y,ne]),es=l.useMemo(()=>Y?.notIndexed.slice(ne,ne+bs)??[],[Y,ne]),pt=l.useMemo(()=>Y?.deindexed.slice(ne,ne+bs)??[],[Y,ne]),Fs=l.useMemo(()=>(I?.urls??[]).slice(ne,ne+bs),[I,ne]),[N,re]=l.useState(!1),[at,Re]=l.useState(null),[gt,rs]=l.useState(null),[Vt,Xt]=l.useState(null);function ko(x,D){const Z=su(x),ce=sm(Z);ce?(rs(ce),Re(null)):(rs(null),Re(Z.message||D))}const Ft=r.find(x=>x.connectionType==="gsc"),ks=(Ft?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),ta=jt.length>0?jt:(xt??[]).map(x=>x.path),si=ta.filter(x=>xt?.some(D=>D.path===x&&D.isSitemapsIndex)).length,Ao=si===1?"Resubmit sitemap index":si>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Po=h.length>0||j.length>0||g.length>0,sa=Zo(),na=el();async function ni(x,D=!1){if(!x){c([]),A("");return}_e(!0);try{const{sites:Z}=await n.fetchQuery({...xl({client:U,path:{name:t}}),staleTime:D?0:$t});c(Z),A(x.propertyId??Z[0]?.siteUrl??""),rs(null)}catch(Z){c([]),ko(Z,"Failed to load Search Console properties")}finally{_e(!1)}}async function sn(x){E(!0);const D=x??se;try{const Z=Ot?$n:os,ce=Ot?0:D,ze={limit:String(Z)};B.startDate&&(ze.startDate=B.startDate),B.endDate&&(ze.endDate=B.endDate),B.query&&(ze.query=B.query),B.page&&(ze.page=B.page),ce>0&&(ze.offset=String(ce)),T&&T!=="all"&&!B.startDate&&(ze.window=T);const Xe=await n.fetchQuery({...nl({client:U,path:{name:t},query:ze}),staleTime:$t}),tt=Xe.rows;Ot?(X(!1),p(tt),_(tt.length),Ne(!0)):(X(ce+tt.length<Xe.totalMatching),p(tt),_(0),Ne(!1))}catch(Z){p([]),X(!1),_(0),Re(Z instanceof Error?Z.message:"Failed to load GSC performance data")}finally{E(!1)}}async function aa(){try{const x={};B.startDate&&(x.startDate=B.startDate),B.endDate&&(x.endDate=B.endDate),T&&T!=="all"&&!B.startDate&&(x.window=T);const D=await n.fetchQuery({...sl({client:U,path:{name:t},query:x}),staleTime:$t});v(D)}catch{v(null)}}async function kn(x=!1){L(!0);try{const D=Le.trim()||void 0,Z={limit:"20"};D&&(Z.url=D);const[ce,ze]=await Promise.all([n.fetchQuery({...ml({client:U,path:{name:t},query:Z}),staleTime:x?0:$t}),n.fetchQuery({...hl({client:U,path:{name:t}}),staleTime:x?0:$t})]);b(ce),f(ze)}catch(D){b([]),f([]),Re(D instanceof Error?D.message:"Failed to load GSC inspection history")}finally{L(!1)}}async function ai(x=!1){ot(!0);try{const[D,Z]=await Promise.all([n.fetchQuery({...rl({client:U,path:{name:t}}),staleTime:x?0:$t}),n.fetchQuery({...ol({client:U,path:{name:t}}),staleTime:x?0:$t}).catch(()=>[])]);Be(D),ps(Z)}catch(D){Be(null),ps([]),Re(D instanceof Error?D.message:"Failed to load coverage data")}finally{ot(!1)}}async function ii(x){re(!0),Re(null);try{const D=await xi(t,{urls:x}),{succeeded:Z,failed:ce,total:ze}=D.summary;Se({title:"Indexing requested",detail:ce===0?`${Z} URL${Z!==1?"s":""} submitted for indexing.`:`${Z}/${ze} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to request indexing")}finally{re(!1)}}async function Ro(){re(!0),Re(null);try{const x=await xi(t,{urls:[],allUnindexed:!0}),{succeeded:D,failed:Z,total:ce}=x.summary;Se({title:"Indexing requested",detail:Z===0?`${D} unindexed URL${D!==1?"s":""} submitted for indexing.`:`${D}/${ce} submitted successfully, ${Z} failed.`,tone:Z===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(x){Re(x instanceof Error?x.message:"Failed to request indexing")}finally{re(!1)}}async function ia(){Oe(!0),Re(null);try{const x=await oa(t);n.setQueryData(ll({client:U,path:{name:t}}),x),We(x.sitemaps),Te(x.summary),Tt(x.preferredSubmissionUrls),Ge(new Set),Ke({}),x.sitemaps.length===0&&Xt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(x){Re(x instanceof Error?x.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function Io(x){const D=Ue.has(x);if(Ge(Z=>{const ce=new Set(Z);return D?ce.delete(x):ce.add(x),ce}),!(D||bt[x])){kt(Z=>new Set(Z).add(x));try{const Z=await oa(t,x);Ke(ce=>({...ce,[x]:Z.sitemaps}))}catch(Z){Re(Z instanceof Error?Z.message:"Failed to load sitemap files")}finally{kt(Z=>{const ce=new Set(Z);return ce.delete(x),ce})}}}async function _s(x){if(!ks||x.length===0)return;const D=[...new Set(x)];Pt(!0),Re(null),G({completed:0,total:D.length});let Z=0,ce=0,ze=0,Xe=null;try{for(let yt=0;yt<D.length;yt+=50){const st=D.slice(yt,yt+50);try{const xe=await cl(t,st);Z+=xe.summary.accepted,ce+=xe.summary.failed,ze+=st.length,G({completed:ze,total:D.length})}catch(xe){ze+=st.length;const gs=st.length,nn=D.length-ze,An=xe instanceof Error?xe.message:"The batch request failed",fs=`${Z} accepted, ${ce} failed, ${gs} unconfirmed, ${nn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Xe=`Sitemap submission stopped after a batch request failed. ${fs} ${An}`,Re(Xe),Se({title:"Sitemap resubmission partially completed",detail:fs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const tt=D.length;Se({title:ce===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ce===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${Z}/${tt} sitemap submissions; ${ce} failed. Indexing is not guaranteed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),fe("")}catch(tt){Re(tt instanceof Error?tt.message:"Failed to submit sitemap to Google")}finally{Pt(!1),G(null),await ia(),Xe&&Re(Xe)}}async function $o(){Pt(!0);const x=xt??[];try{const D=x.filter(ce=>ce.isSitemapsIndex),Z=[];for(let ce=0;ce<D.length;ce+=4)(await Promise.all(D.slice(ce,ce+4).map(async Xe=>{const tt=bt[Xe.path];if(tt)return tt;const yt=await oa(t,Xe.path);return Ke(st=>({...st,[Xe.path]:yt.sitemaps})),yt.sitemaps}))).forEach((Xe,tt)=>{Z.push(...Xe.length>0?Xe.map(yt=>yt.path):[D[ce+tt].path])});await _s([...x.filter(ce=>!ce.isSitemapsIndex).map(ce=>ce.path),...Z])}catch(D){Re(D instanceof Error?D.message:"Failed to load sitemap files"),Pt(!1)}}async function ri(x){Mt(!0),Re(null);try{await dl(t,"gsc",x),await ft(n,"google"),o(D=>D.map(Z=>Z.connectionType==="gsc"?{...Z,sitemapUrl:x}:Z)),Se({title:"Default sitemap updated",detail:x,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to set the default sitemap")}finally{Mt(!1)}}async function oi(x){try{await na.mutateAsync({projectName:t,projectLabel:t,opts:x?{sitemapUrl:x}:void 0})}catch{}}async function li(){Qe(!0),Re(null);try{const[x,D]=await Promise.all([Sr().catch(()=>null),n.fetchQuery({...Ba({client:U,path:{name:t}}),staleTime:$t}).catch(()=>[])]);i(!!x?.google?.configured),o(D);const Z=D.find(ce=>ce.connectionType==="gsc");await Promise.all([ni(Z),sn(),aa(),kn(),ai(),Z?.propertyId?ia():Promise.resolve()])}finally{Qe(!1)}}l.useEffect(()=>{li()},[t,s]),l.useEffect(()=>{le(0),ee(null),R(x=>x.startDate||x.endDate?{...x,startDate:"",endDate:""}:x),W(x=>x+1),aa()},[T]);const ci=l.useRef(!1);l.useEffect(()=>{if(!ci.current){ci.current=!0;return}le(0),et.setPage(1),sn(0)},[ie]);function ra(x){const D=z===x?null:x;ee(D),R(Z=>({...Z,startDate:D??"",endDate:D??""})),W(Z=>Z+1)}const di=l.useRef(!1);l.useEffect(()=>{if(!di.current){di.current=!0;return}le(0),sn(0)},[Yt]);async function ui(){if(!a){Re("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),Re(null),Xt(null);try{let x=function(xe){if(xe.source!==ce||xe.origin!==ze||!xe.data||typeof xe.data!="object")return;const gs=xe.data;gs.type!==am||gs.connectionType!=="gsc"||st(!0)};const{authUrl:D,redirectUri:Z}=await il(t,"gsc");if(!D.startsWith("https://accounts.google.com/")){Re("Unexpected OAuth redirect URL. Please try again.");return}const ce=window.open(D,"_blank","width=600,height=700");if(!ce){window.location.assign(D);return}const ze=Z?new URL(Z).origin:window.location.origin;let Xe=!1,tt=null;const yt=()=>{tt!==null&&window.clearInterval(tt),window.removeEventListener("message",x)},st=async xe=>{if(!Xe){Xe=!0,yt(),Xt(xe?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await ft(n,"google"),await li()}finally{Xt(null)}}};window.addEventListener("message",x),Xt("Finish the Google consent flow in the popup. This page will refresh automatically."),tt=window.setInterval(()=>{ce.closed&&st(!1)},1e3)}catch(x){Re(x instanceof Error?x.message:"Failed to start OAuth flow")}finally{we(!1)}}async function To(){Re(null),Xt(null);try{await al(t,"gsc"),await ft(n,"google"),o(x=>x.filter(D=>D.connectionType!=="gsc")),c([]),A("")}catch(x){Re(x instanceof Error?x.message:"Failed to disconnect")}}async function Mo(){if(q){$e(!0),Re(null);try{await pl(t,"gsc",q),await ft(n,"google"),o(x=>x.map(D=>D.connectionType==="gsc"?{...D,propertyId:q}:D)),Se({title:"GSC property updated",detail:`${t} is now linked to ${q}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(x){Re(x instanceof Error?x.message:"Failed to save GSC property")}finally{$e(!1)}}}async function Lo(){Re(null),Xt(null);try{await sa.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:K||void 0}}),await ft(n,"gsc")}catch{}}async function mi(){if(d.trim()){qe(!0),Re(null),Xt(null);try{const x=await ul(t,d.trim());await ft(n,"gsc"),O(x),y(""),await kn()}catch(x){Re(x instanceof Error?x.message:"Failed to inspect URL")}finally{qe(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),gt&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:gt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:gt.message}),(Ts(gt.enableUrl)||Ts(gt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ts(gt.enableUrl)&&e.jsx("a",{href:Ts(gt.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Ts(gt.indexingApiUrl)&&e.jsx("a",{href:Ts(gt.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>rs(null),children:"×"})]})}),at&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[at,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Re(null),children:"×"})]}),Vt&&e.jsxs("div",{className:"mb-3 rounded-lg border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-sm text-positive",children:[Vt,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Xt(null),children:"×"})]}),Pe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ft?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:Ft.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",Y?.lastInspectedAt?qt(Y.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Me(To),children:"Disconnect"})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ue,onClick:Me(ui),children:ue?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(as,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),(Ft||Po)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Je,{text:`Tile percentages compare the trailing half of the selected window with the prior equal-length half. The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${$n.toLocaleString()} matching rows while the table shows ${os} per page.`})]}),u?.window?.startDate&&u.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[u.window.startDate," to ",u.window.endDate,(u.window.daysSinceLatestData??0)>0&&` · latest data ${u.window.daysSinceLatestData} day${u.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(to,{windows:nm,value:T,onChange:x=>{F(x),le(0),et.setPage(1)},label:"Search Console time period",formatOption:x=>x==="all"?"All":x}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Ce,onClick:()=>{le(0),et.setPage(1),sn(0),aa()},children:Ce?"Loading…":"Apply filters"})]})]}),u&&u.daily.length>0&&(()=>{const{totals:x,daily:D,trends:Z,periodComparison:ce}=u,Xe=Ri.filter(xe=>$.includes(xe.key)).map(xe=>({dataKey:xe.key,label:xe.label,color:xe.color,axisId:xe.key,inverted:xe.inverted,formatValue:xe.format,trend:ye?Z?.[xe.key]??null:null})),tt=xe=>x[xe]??null,yt=new Map(D.map(xe=>[xe.date,xe])),st=D.length===0?[]:lu(D[0].date,D[D.length-1].date).map(xe=>yt.get(xe)??{date:xe});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Ri.map(xe=>{const gs=$.includes(xe.key),nn=tt(xe.key),An=nn===null;return e.jsxs("button",{type:"button","aria-pressed":gs,disabled:An,className:`rounded-md border px-3 py-2 text-left transition-colors ${gs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${An?"cursor-not-allowed opacity-50":""}`,onClick:()=>{H(fs=>fs.includes(xe.key)?fs.length===1?fs:fs.filter(Do=>Do!==xe.key):[...fs,xe.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:gs?xe.color:"transparent",border:`1px solid ${xe.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:xe.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:nn===null?"—":xe.format(nn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:rm(ce,xe.key,xe.inverted)})]},xe.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:ye,onChange:xe=>ge(xe.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Er,{data:st,xKey:"date",series:Xe,xTickFormatter:gn,labelFormatter:Ut,onSelectX:ra,selectedX:z})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:D.map(xe=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":z===xe.date,onClick:()=>ra(xe.date),children:[Ut(xe.date),": ",xe.clicks," clicks, ",xe.impressions," impressions"]},xe.date))}),z&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ut(z)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ra(z),children:["Show all ",x.days," days"]})]}),x.position!==null&&(x.positionDays??x.days)<x.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",x.positionDays," of ",x.days," days. The rest have no property-level position recorded."]}),(x.position===null||x.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:B.startDate,onChange:x=>R(D=>({...D,startDate:x.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:B.endDate,onChange:x=>R(D=>({...D,endDate:x.target.value}))}),e.jsx(Hs,{value:B.query,onChange:x=>R(D=>({...D,query:x})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Hs,{value:B.page,onChange:x=>R(D=>({...D,page:x})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(Ls).map(x=>e.jsx("th",{className:"text-right","aria-sort":wt?.key===x?wt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{et.setPage(1),hs(D=>D?.key===x?D.dir==="desc"?{key:x,dir:"asc"}:null:{key:x,dir:"desc"})},children:[tl[x],wt?.key===x?wt.dir==="desc"?" ↓":" ↑":""]})},x))]})}),e.jsx("tbody",{children:xs.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:x.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Un,{value:x.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(x.ctr)?x.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.position.toFixed(1)})]},`${x.date}:${x.query}:${x.page}:${D}`))})]})}),e.jsx(Es,{page:ae?et.page:Math.floor(se/os)+1,pageSize:os,visibleRows:xs.length,totalRows:ae?Ae:void 0,hasNextPage:ae?void 0:de,disabled:Ce,itemLabel:ae?"matches":"rows",onPageChange:x=>{if(ae){et.setPage(x);return}const D=(x-1)*os;le(D),sn(D)}}),ae&&Ae>=$n?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",$n.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Je,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Y&&Y.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:N,onClick:()=>{Ro()},children:N?"Requesting…":`Request indexing (${Y.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:mt,onClick:()=>{ai(!0)},children:mt?"Loading…":"Reload saved coverage"})]})]}),Y&&Y.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const x=Y.summary.indexed+Y.summary.notIndexed,D=x>0?Y.summary.indexed/x:0,Z=x>0?Y.summary.notIndexed/x:0,ce=54,ze=2*Math.PI*ce,Xe=ze*(1-D),tt=ze*Z,yt=ze*D;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Ht.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:qs.positiveDeep,strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Xe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),Y.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Ht.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${ze-tt}`,strokeDashoffset:-yt,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(D*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(Y.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(Y.reasonGroups??[]).length," ",(Y.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),Y.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(x=>{const D=x==="indexed"?Y.indexed.length:x==="notIndexed"?Y.notIndexed.length:Y.deindexed.length,Z=x==="indexed"?"Indexed":x==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":nt===x,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${nt===x?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{ms(x),Zt(null)},children:[Z," (",D,")"]},x)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[nt==="indexed"&&Y.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:Ee.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.crawlTime?x.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.isMobileFriendly===!0?"Yes":x.isMobileFriendly===!1?"No":"—"})]},x.id))})]}),nt==="notIndexed"&&!dt&&(Y.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(Y.reasonGroups??[]).map(x=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>Zt(x.reason),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),Zt(x.reason))},tabIndex:0,role:"button","aria-label":`View ${x.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:x.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.count})]},x.reason))})]}),nt==="notIndexed"&&!dt&&(Y.reasonGroups??[]).length===0&&Y.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:es.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"})]},x.id))})]}),nt==="notIndexed"&&dt&&(()=>{const x=(Y.reasonGroups??[]).find(D=>D.reason===dt);return x?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>Zt(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:x.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[x.count," affected page",x.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:N,onClick:()=>{ii(x.urls.map(D=>D.url))},children:N?"Requesting…":`Request indexing (${x.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Fs.map(D=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:D.url}),e.jsx("td",{className:"text-secondary",children:D.crawlTime?D.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:N,onClick:()=>{ii([D.url])},title:"Request indexing",children:"Index"})})]},D.id))})]})]}):null})(),nt==="deindexed"&&Y.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:pt.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState}),e.jsx("td",{className:"text-secondary",children:x.currentState}),e.jsx("td",{className:"text-secondary",children:x.transitionDate.split("T")[0]})]},`${x.url}-${D}`))})]}),(nt==="indexed"&&Y.indexed.length===0||nt==="notIndexed"&&!dt&&Y.notIndexed.length===0||nt==="deindexed"&&Y.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Es,{page:te,pageSize:bs,visibleRows:Math.min(bs,Q.length-ne),totalRows:Q.length,onPageChange:be,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Dt,onClick:()=>is(x=>!x),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Dt?"Hide snapshots":St.length>0?`View ${St.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",Y.summary.indexed.toLocaleString()," indexed, ",Y.summary.notIndexed.toLocaleString()," not indexed.",ve&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ve.indexed>=0?"+":"",ve.indexed.toLocaleString()," indexed, ",ve.notIndexed>=0?"+":"",ve.notIndexed.toLocaleString()," not indexed."]})]}),Dt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:St.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:St.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.notIndexed.toLocaleString()})]},x.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:mt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Je,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:De||!Ft?.propertyId,onClick:()=>{ia()},children:De?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:ke,onChange:x=>fe(x.target.value),onKeyDown:x=>x.key==="Enter"&&void _s([ke.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!ks||ct||!ke.trim(),onClick:()=>{_s([ke.trim()])},children:ct?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ks||ct||ta.length===0,onClick:()=>{_s(ta)},children:ct?"Resubmitting…":Ao}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ks||ct||!xt?.length,onClick:()=>{$o()},children:"Resubmit all files"}),Ve&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ve.indexes," index",Ve.indexes===1?"":"es",", ",Ve.files," file",Ve.files===1?"":"s"]}),lt&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",lt.completed,"/",lt.total]})]}),!ks&&Ft&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Me(ui),children:"Reconnect"})]}),xt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:xt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:vt,onChange:x=>{At(x),Gt.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Gt.rows.flatMap(x=>{const D=Ii(x),Z=$i(x),ce=Ti(x),ze=bt[x.path]??[],Xe=Ue.has(x.path),tt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Un,{value:x.path})}),e.jsx("td",{className:"text-secondary",children:x.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Xe,"aria-label":`${Xe?"Collapse":"Expand"} files in ${x.path}`,onClick:()=>{Io(x.path)},children:Nt.has(x.path)?"Loading…":`${Xe?"▾":"▸"} Index${bt[x.path]?` (${ze.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ce}),e.jsx("td",{className:"text-secondary",children:x.lastSubmitted?x.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.lastDownloaded?x.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:D.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:Z||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!ks||ct,onClick:()=>{_s([x.path])},children:x.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Ft?.sitemapUrl===x.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:he,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ri(x.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:na.isPending,onClick:()=>{oi(x.path)},children:"Inspect URLs"})]})})]},x.path),yt=x.isSitemapsIndex&&Xe?ze.map(st=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Un,{value:st.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ti(st)}),e.jsx("td",{className:"text-secondary",children:st.lastSubmitted?st.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:st.lastDownloaded?st.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Ii(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:$i(st)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!ks||ct,onClick:()=>{_s([st.path])},children:"Resubmit"}),Ft?.sitemapUrl===st.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:he,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ri(st.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:na.isPending,onClick:()=>{oi(st.path)},children:"Inspect URLs"})]})})]},`${x.path}:${st.path}`)):[];return[tt,...yt]})})]}),e.jsx(Es,{page:Gt.page,pageSize:os,visibleRows:Gt.rows.length,totalRows:Gt.totalRows,onPageChange:Gt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:d,onChange:x=>y(x.target.value),onKeyDown:x=>x.key==="Enter"&&void mi()}),e.jsx(P,{type:"button",size:"sm",disabled:je||!Ft?.propertyId||!d.trim(),onClick:Me(mi),children:je?"Inspecting…":"Inspect URL"})]}),k&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:k.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:k.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:hi(k.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:qt(k.crawlTime)})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:M,onClick:()=>{kn(!0)},children:M?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:Le,onChange:x=>Fe(x.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:M,onClick:()=>{kn(!0)},children:"Apply filter"})]}),j.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:j.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-neutral",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:hi(x.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:qt(x.inspectedAt)})]},x.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),g.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:g.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:x.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:qt(x.transitionDate)})]},`${x.url}:${x.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ft&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>Wt(x=>!x),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${Lt?"rotate-90":""}`,"aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted",children:"Setup & Configuration"})]})}),Lt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Je,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:q,disabled:Ze||m.length===0,onChange:x=>A(x.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ze?"Loading properties…":"No properties available"}):m.map(x=>e.jsxs("option",{value:x.siteUrl,children:[x.siteUrl," · ",x.permissionLevel]},x.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ze,onClick:()=>{ni(Ft,!0)},children:Ze?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!q||He,onClick:Me(Mo),children:He?"Saving…":"Save property"})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:S,onChange:x=>V(x.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:K,onChange:x=>w(x.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:sa.isPending||!Ft.propertyId,onClick:Me(Lo),children:sa.isPending?"Queueing…":"Queue sync"}),!Ft.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const lm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function cm({projectName:t,projectId:s}){const n=Cs(),[a,i]=l.useState(null),[r,o]=l.useState(null),[m,c]=l.useState(!1),h=Ie(Ba({client:U,path:{name:t}})),p=h.data?.find(_=>_.connectionType==="gbp"),u=!!p,v=a?{locationName:a}:void 0,j=Ie({...gl({client:U,path:{name:t}}),enabled:u}),b=Ie({...fl({client:U,path:{name:t},query:v}),enabled:u}),g=Ie({...bl({client:U,path:{name:t},query:v}),enabled:u}),f=Ie({...vl({client:U,path:{name:t},query:v}),enabled:u}),k=Ie({...yl({client:U,path:{name:t},query:v}),enabled:u}),O=Ie({...jl({client:U,path:{name:t},query:v}),enabled:u}),q=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>Nl(t),enabled:u});function A(){ft(n,"gbp")}const d=Et({...wl(),onSuccess:_=>{Cr({id:_.runId,projectId:s,kind:Os["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),y=l.useSyncExternalStore(kr,Kn,Kn),S=Object.values(y.runs).some(_=>_.kind===Os["gbp-sync"]&&_.projectId===s),V=d.isPending||S,K=Et({...Sl(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!j.data)return;const _=j.data.locations.filter(ae=>ae.selected);(_.length<=1||!_.some(ae=>ae.locationName===a))&&i(null)},[a,j.data]),l.useEffect(()=>{if(!r||!j.data)return;(a?[a]:j.data.locations.filter(ae=>ae.selected).map(ae=>ae.locationName)).includes(r)||o(null)},[r,j.data,a]),h.isLoading)return null;if(!p){const _=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:_.map((ae,Ne)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:Ne+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ae.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ae.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ae.note})]})]},ae.title))})]})})}const w=b.data,T=j.data?.locations??[],F=T.filter(_=>_.selected),$=g.data?.keywords??[],H=f.data?.lodging??[],ye=k.data?.placeActions??[],ge=O.data?.places??[],z=T.length>0?T[0].accountName:p.domain,ee=a?T.find(_=>_.locationName===a)?.displayName??null:null,ie=a?T.filter(_=>_.locationName===a):F,W=new Set(ie.map(_=>_.locationName)),B=H.filter(_=>W.has(_.locationName)),R=ye.filter(_=>W.has(_.locationName)),se=ge.filter(_=>W.has(_.locationName)),le=new Set(F.map(_=>_.locationName)),de=a?$:$.filter(_=>le.has(_.locationName)),X=!a&&F.length>1,Ae=(q.data??[]).filter(_=>!_.dismissed&&lm.has(_.type)&&(!ee||_.query===ee||_.query===a||_.title.startsWith(ee)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Je,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:V,onClick:()=>d.mutate({client:U,path:{name:t},body:{}}),children:V?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[z?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:z})," · "]}):null,j.data?`${j.data.totalSelected} of ${j.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:_=>i(_.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),F.map(_=>e.jsx("option",{value:_.locationName,children:_.displayName},_.id))]})]}),F.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[Ae.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ae.map(_=>e.jsx("div",{className:["insight-card",Nm(_.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[_.title,_.recommendation?.reason&&e.jsx(Je,{text:_.recommendation.reason})]})},_.id))]}),w&&e.jsx(km,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(dm,{summary:w.profileCompleteness}),ie.length>0&&e.jsx(um,{locations:ie,lodging:B,places:se,placeActions:R,expandedLocation:r,onToggleExpanded:_=>{o(ae=>ae===_?null:_)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),de.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),X&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:de.slice(0,25).map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:_.keyword}),X&&e.jsx("td",{className:"text-muted",children:T.find(ae=>ae.locationName===_.locationName)?.displayName??_.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:_.valueCount!==null?_.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",_.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[_.periodStart,"–",_.periodEnd]})]},`${_.locationName}:${_.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>c(_=>!_),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",T.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:T.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!J()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:T.map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:_.displayName}),e.jsx("td",{className:"text-muted",children:_.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:_.selected?"positive":"neutral",children:_.selected?"Tracked":"Not tracked"})}),!J()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:K.isPending,onClick:()=>K.mutate({client:U,path:{name:t,locationName:_.locationName},body:{selected:!_.selected}}),children:_.selected?"Untrack":"Track"})})]},_.id))})]})})]})]})})}function dm({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:on(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:on(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:on(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:on(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:on(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Je,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${jm(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function um({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const o=new Map(s.map(h=>[h.locationName,h])),m=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const p=c.get(h.locationName)??[];p.push(h),c.set(h.locationName,p)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Je,{text:J()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const p=o.get(h.locationName)??null,u=m.get(h.locationName)??null,v=c.get(h.locationName)??[],j=i===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(oe,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(oe,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:so(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(hm,{location:h})}),e.jsx("td",{children:e.jsx(xm,{lodging:p})}),e.jsx("td",{children:e.jsx(gm,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(bm,{actions:v})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>r(h.locationName),children:j?"Hide":"Details"})})]}),j&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(ym,{location:h,lodging:p,place:u,placeActions:v})})})]},h.id)})})]})})]})}function mm(t){return[{label:"Description",tone:Ms(t.description)?"positive":"neutral",value:Ms(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Ms(t.primaryPhone)?"positive":"neutral",value:Ms(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Ms(t.websiteUri)?"positive":"neutral",value:Ms(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function hm({location:t}){const s=mm(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function xm({lodging:t}){return e.jsx(Ka,{...pm(t)})}function pm(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function gm({place:t,mapsUri:s}){return e.jsx(Ka,{...fm(t,s)})}function fm(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function bm({actions:t}){return e.jsx(Ka,{...vm(t)})}function vm(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function Ka({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function ym({location:t,lodging:s,place:n,placeActions:a}){const i=s?Sm(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(ha,{title:"Owner profile · Business Information",children:[e.jsx(Rt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Rt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Rt,{label:"Description",value:Ms(t.description)?t.description:"Not returned"}),e.jsx(Rt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Rt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Rt,{label:"Open status",value:so(t.openStatus)}),e.jsx(Rt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(ha,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Last checked",value:Mi(s.syncedAt)}),e.jsx(Rt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Rt,{label:"Populated groups",value:i.length>0?i.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(ha,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Places tier",value:n.tier}),e.jsx(Rt,{label:"Last checked",value:Mi(n.syncedAt)}),e.jsx(Rt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Yn(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Yn(r.providerType),r.uri?` · ${wm(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function ha({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Rt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function on(t,s,n){return t===s?"positive":t===0?n:"caution"}function jm(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Nm(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Ms(t){return typeof t=="string"&&t.trim().length>0}function so(t){return t?Yn(t):"Not returned"}function Yn(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function wm(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Mi(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Sm(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Cm(n)).map(([s])=>Yn(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Cm(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function km({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=Cl.filter(b=>(a[b]??0)>0),r=kl.filter(b=>(a[b]??0)>0),o=Object.keys(a).filter(b=>(a[b]??0)>0&&Al(b)==="other").sort((b,g)=>(a[g]??0)-(a[b]??0)),m=Object.keys(a).filter(b=>(a[b]??0)===0).sort(),c=n.map(b=>{const g={date:b.date};for(const[f,k]of Object.entries(b.metrics))g[f]=k;return g}),h=n.find(b=>b.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,u=c.length>0,v=s.dataThroughDate?`Data through ${Ut(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,j=[...i,...o];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),v&&e.jsx("span",{className:"text-[11px] text-muted",children:v})]}),!u||i.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Li,{data:c,metrics:i,kind:"line",firstPending:h,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:j.map(b=>e.jsxs("span",{className:"text-sm text-secondary",children:[zn(b)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[b]??0).toLocaleString()})]},b))})]})]}),u&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Li,{data:c,metrics:r,kind:"area",firstPending:h,lastDate:p})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(b=>zn(b)).join(", ")]})]})}function Li({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Fr,{stroke:qr,vertical:!1}),e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn,minTickGap:24}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(r,o)=>[typeof r=="number"?r.toLocaleString():String(r??0),zn(String(o??""))]}),e.jsx(Gr,{wrapperStyle:{fontSize:11,color:Ht.text},formatter:r=>zn(r)}),a&&i&&e.jsx(nu,{x1:a,x2:i,fill:Ht.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Ht.textDim,fontSize:10}}),s.map((r,o)=>n==="line"?e.jsx(_r,{type:"monotone",dataKey:r,stroke:rt[o%rt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(zs,{type:"monotone",dataKey:r,stackId:"reach",stroke:rt[o%rt.length],fill:rt[o%rt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function Am(t){return Or(us(String(t)))}function Pm(t){return Ss(us(String(t)))}function xa({children:t,label:s="More info",placement:n="top",className:a}){const i=l.useId(),[r,o]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Wd,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Tn=os;function Us(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function pa(t){return t.toLocaleString()}function Rm(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Im(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function $m(t){const s=t.filter(n=>n.kind===Os["backlink-extract"]&&!Ar(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Tm(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function Mm({projectName:t}){const[s,n]=l.useState(null),[a,i]=l.useState(null),[r,o]=l.useState([]),[m,c]=l.useState(null),[h,p]=l.useState(null),[u,v]=l.useState(null),[j,b]=l.useState(Date.now()),[g,f]=l.useState(0),[k,O]=l.useState(!0),[q,A]=l.useState(!1),[d,y]=l.useState(null),S=l.useCallback(async()=>{O(!0),y(null);try{const[z,ee,ie,W,B]=await Promise.all([Pl().catch(()=>null),Rl(t,{excludeCrawlers:!0}).catch(()=>null),Il(t,{limit:Tn,offset:g,excludeCrawlers:!0}).catch(se=>{if(se instanceof Zs&&se.code==="NOT_FOUND")return null;throw se}),$l(t).catch(()=>[]),Tl(t).catch(()=>[])]);c(z),n(ee),i(ie),o(W);const R=$m(B);p(R)}catch(z){y(z instanceof Error?z.message:"Failed to load backlinks")}finally{O(!1)}},[t,g]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!h)return;const z=h.id;let ee=!1;const ie=async()=>{try{const B=await Ta(z);if(ee)return;Ar(B.status)?(p(null),v(B),await S()):p(R=>R?.id===B.id?{...R,...B}:R)}catch{}},W=window.setInterval(()=>{ie()},3e3);return()=>{ee=!0,window.clearInterval(W)}},[h,S]),l.useEffect(()=>{if(!h)return;const z=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(z)},[h]),l.useEffect(()=>{if(!u||u.status==="failed")return;const z=window.setTimeout(()=>v(null),1e4);return()=>window.clearTimeout(z)},[u]);async function V(){A(!0),y(null);try{const z=await Ll(t);p(z)}catch(z){z instanceof Zs&&z.code==="MISSING_DEPENDENCY"?y("DuckDB is not installed. Visit the Backlinks admin page to install it."):y(z instanceof Error?z.message:"Failed to trigger extract")}finally{A(!1)}}const K=l.useMemo(()=>r.slice().sort((z,ee)=>z.queriedAt.localeCompare(ee.queriedAt)).map(z=>({date:z.queriedAt,linkingDomains:z.totalLinkingDomains})),[r]),w=a?.rows??[],T=a?.total??0,F=s?.excludedLinkingDomains??0,$=Math.floor(g/Tn)+1;return l.useEffect(()=>{g>0&&g>=T&&f(0)},[g,T]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),d&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:d})}),h&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Qd,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(oe,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Tm(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",j]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),u&&!h&&e.jsx(pe,{className:`surface-card p-4 mb-4 ${u.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[u.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Lr,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${u.status==="failed"?"text-negative":"text-positive"}`,children:u.status==="failed"?"Extract failed":"Extract complete"}),u.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Ml(u.error)}):u.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return k?e.jsx(pe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):ye()}function ye(){const z=s!==null&&s.totalLinkingDomains>0,ee=u?.status==="failed",ie=s!==null&&s.totalLinkingDomains===0&&!ee,W=m?.status==="ready",B=m?.status==="failed",R=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return z?ge(e.jsxs(e.Fragment,{children:[!J()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Dr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsx(xa,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!J()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Open admin"})})]})):e.jsx(pe,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Hd,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Set up backlinks"})})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"View sync status"})})})]}),B&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})})})]}),W&&!R&&!ie&&!ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:m.release})," is ready. Run an extract for this project."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Hn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Run extract"]}),e.jsx(xa,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!J()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})})})]}),ie&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Hn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsxs(xa,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function ge(z){if(!s)return null;const ee="Linking hosts",ie="linking hosts",W="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:pa(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",ie]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:pa(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ie," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Rm(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ie," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",W," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Im(s.queriedAt),F>0&&e.jsxs(e.Fragment,{children:[" · ",F," excluded domain",F===1?"":"s"]})]}),K.length>=2&&e.jsxs(pe,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:K,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:rt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:rt[0],stopOpacity:0})]})}),e.jsx(vn,{dataKey:"date",tick:ns,stroke:Gs,tickFormatter:Am}),e.jsx(yn,{tick:ns,stroke:Gs,allowDecimals:!1}),e.jsx(jn,{contentStyle:Ws.contentStyle,labelStyle:Ws.labelStyle,itemStyle:Ws.itemStyle,labelFormatter:Pm}),e.jsx(zs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:rt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(pe,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:ee})]})}),e.jsxs("tbody",{children:[w.map(B=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:B.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:pa(B.numHosts)})]},B.linkingDomain)),w.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:F>0&&T===0?`Every referring domain in this ${W} was a crawler/proxy host (${F} hidden).`:`No referring domains in this ${W}.`})})]})]})}),e.jsx(Es,{page:$,pageSize:Tn,visibleRows:w.length,totalRows:T,onPageChange:B=>f((B-1)*Tn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:z})]})}}function Lm({projectName:t}){const s=Ie({...Dl({client:U,path:{name:t}}),staleTime:Pr}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:Va(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:i,providersMentioning:r,providersConfigured:o}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",i," of ",o," engines",e.jsx(Je,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",r," of ",o," engine answers",e.jsx(Je,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(Dm,{data:n}),e.jsx(Em,{data:n}),n.competitorGaps.length>0&&e.jsx(Fm,{data:n})]})}function Dm({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Mn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Mn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Mn,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Mn,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Mn({label:t,value:s,helper:n,tone:a}){const i=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Em({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const i of a.providers)n.add(i.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(qm,{}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(Js,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(Yd,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Om,{provider:i})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function qm(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!1,tone:"cited"}),e.jsx(Qs,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Om({provider:t}){const s=Gm(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Qs,{active:t.cited,tone:"cited"}),e.jsx(Qs,{active:t.mentioned,tone:"mentioned"})]})}function Gm(t){return t.cited&&t.mentioned?"Cited in sources and mentioned in answer":t.cited?"Cited in sources, not mentioned in answer":t.mentioned?"Mentioned in answer, not in sources":"Not cited and not mentioned"}function Qs({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Fm({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Je,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(Js,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Sn="__cited__",Cn="__mentioned__",Qt="__mentionShare__";function no(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:us(n),end:us(a),sweepCount:s.sweepCount??1}}function Xn(t){const s=no(t);if(!s)return"Sweep date unavailable";const n=Ss(s.start),a=Ss(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function _m(t){const s=no(t);return s?Or(s.start):""}function tn(t){return t.trim().toLowerCase()}function Ea(t){return Math.round(t*1e3)/10}function qa(t){return t.byProvider??{}}function Um(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?Sn:Cn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[c]:Ea(u[h])})),series:[c],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(c=>Object.keys(qa(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},p=qa(c);for(const u of o){const v=p[u];h[u]=v?Ea(v[r]):null}return h}),series:o,hasData:a,singleBucket:i}}function ao(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Bm(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Vm(t){return t.servedModelAttribution??{}}function Km(t){return t.modelServiceMismatch??{}}function zm(t){return t.modelPointerChanges??{}}function Qm(t){return t.length>0?t.join(", "):null}function Di(t,s){const n=tn(s);return Object.entries(t).find(([a])=>tn(a)===n)?.[1]}function ls(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function Hm(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Di(qa(a),s))continue;const i=ao(a);return i?Di(i,s)??null:null}return null}function Wm(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const i of a.events){const r=s.get(i.bucketStartDate)??[];r.push({provider:n,event:i}),s.set(i.bucketStartDate,r)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((i,r)=>i.provider.localeCompare(r.provider)||i.event.observedAt.localeCompare(r.event.observedAt))}))}function Ym(t){const s={},n=[];for(const[a,i]of Object.entries(t)){const r=i.events.filter(o=>!o.fromPreWindowAnchor);for(const o of i.events)o.fromPreWindowAnchor&&n.push({provider:a,event:o});r.length>0&&(s[a]={...i,events:r})}return{buckets:Wm(s),beforeWindow:n.sort((a,i)=>a.event.observedAt.localeCompare(i.event.observedAt)||a.provider.localeCompare(i.provider))}}function Xm(t){let s=0,n=0;for(const a of Object.values(t))s+=a.events.length,n+=a.eventTotal??a.events.length;return{shown:s,total:n}}function Jm(t){const s=[];for(const[n,a]of Object.entries(t)){const i=a.eventTotal??a.events.length;i>a.events.length&&s.push({provider:n,shown:a.events.length,total:i})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Zm(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[Qt]:i?.rate==null?null:Ea(i.rate)}}),n=s.map(a=>a[Qt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Qt],hasData:n.length>0,singleBucket:n.length===1}}function eh(t,s,n){return s==="mentionShare"?Zm(t):Um(t,s,n)}function Ei(t,s){for(let n=t.length-1;n>=0;n--){const a=t[n][s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function qi(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Oi(t){return t>0?`+${t}`:`${t}`}function th(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Oi(n.delta)} on ${qi(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Oi(s.delta)} on ${qi(s.date)})`}const sh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],nh=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],ah=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"On non-brand queries, the share of answer-text brand mentions for you and tracked competitors that were you. Pooled only when query classification is unavailable."}],za=rt[2],ih="var(--chart-tooltip-bg)",rh={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ds(t){const s=tn(t);return rh[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Ns(t){return Math.round(t*10)/10}function oh(t){return t===Sn||t===Cn||t===Qt}function io(t){return t===Sn?"Cited":t===Cn?"Mentioned":t===Qt?"Mention share":ds(t)}function dn(t,s){return t===Sn?qs.positive:t===Cn?rt[1]:t===Qt?za:Zd(tn(t),s)}function lh(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function ch(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
1
|
+
import{r as l,j as e,L as as,n as Cs,u as Ie,o as Et,B as yr,C as Eo,h as qo,k as Oo,D as Go}from"./vendor-tanstack-Dock0eH1.js";import{M as jr,I as Je,T as oe,t as Fo,a as _o,u as Nr,C as Uo,P as Js,B as P,h as Bo,b as Vo,c as Ko,d as pe,i as J,e as ft,f as Me,g as an,j as zo,k as U,l as Qo,m as Ho,n as Wo,o as Yo,p as wr,q as Xo,r as Jo,S as Ls,s as Zo,v as el,w as Ts,x as qt,y as tl,z as hi,A as Sr,G as $t,D as Ba,E as sl,F as nl,H as al,J as il,K as xi,L as Se,N as rl,O as ol,Q as oa,R as ll,U as cl,V as dl,W as ul,X as ml,Y as hl,Z as xl,_ as pl,$ as gl,a0 as fl,a1 as bl,a2 as vl,a3 as yl,a4 as jl,a5 as Nl,a6 as Cr,a7 as Os,a8 as wl,a9 as kr,aa as Kn,ab as Sl,ac as Ye,ad as Cl,ae as kl,af as Al,ag as zn,ah as Pl,ai as Rl,aj as Il,ak as Zs,al as $l,am as Tl,an as Ml,ao as Ar,ap as Ta,aq as Ll,ar as Pr,as as Dl,at as Va,au as El,av as ql,aw as Ol,ax as Gl,ay as Fl,az as _l,aA as Ul,aB as hn,aC as Ds,aD as Bl,aE as Vl,aF as Kl,aG as zl,aH as Rr,aI as Ql,aJ as Hl,aK as Wl,aL as Yl,aM as Xl,aN as Ir,aO as Jl,aP as Zl,aQ as ec,aR as tc,aS as sc,aT as nc,aU as ac,aV as ic,aW as rc,aX as oc,aY as lc,aZ as cc,a_ as dc,a$ as uc,b0 as mc,b1 as hc,b2 as xc,b3 as pc,b4 as gc,b5 as fc,b6 as ts,b7 as bc,b8 as it,b9 as vc,ba as yc,bb as jc,bc as Nc,bd as wc,be as Sc,bf as Cc,bg as kc,bh as Ac,bi as Pc,bj as Rc,bk as Ic,bl as $c,bm as Tc,bn as Mc,bo as Lc,bp as Dc,bq as Ec,br as qc,bs as Oc,bt as Gc,bu as Fc,bv as _c,bw as Uc,bx as Bc,by as Vc,bz as Kc,bA as zc,bB as Qc,bC as Hc,bD as Wc,bE as Yc,bF as Xc,bG as Jc,bH as Zc,bI as ed,bJ as td,bK as sd,bL as la,bM as nd,bN as ad,bO as pi,bP as id,bQ as rd,bR as od,bS as ld,bT as cd,bU as dd,bV as ud,bW as md,bX as hd,bY as xd,bZ as pd,b_ as gd,b$ as $r,c0 as fd,c1 as bd,c2 as vd,c3 as yd,c4 as jd,c5 as Nd,c6 as wd,c7 as gi,c8 as Sd,c9 as ca,ca as Cd,cb as kd,cc as Ad,cd as Pd,ce as Rd,cf as Id,cg as $d,ch as Tr,ci as Td,cj as Md,ck as Ld,cl as Dd,cm as Ed,cn as qd,co as Pn,cp as Od,cq as Gd,cr as Fd,cs as fi,ct as _d}from"./index-xtxQtZRo.js";import{R as Ud}from"./RunRow-B39IK7hK.js";import{u as pn,D as Hs,a as Es,b as Mr,M as Un,c as os,S as Bd}from"./SiteHealthSection-Bx7yVNMQ.js";import{e as Vd,q as Qn,U as Kd,r as zd,L as Qd,s as Lr,i as Hd,P as Hn,D as Dr,t as Wd,u as Yd,E as Xd,C as Wn,v as Jd}from"./vendor-lucide-nYKv-BB7.js";import{f as gn,C as Gs,a as ns,b as Ut,c as Ws,d as Ht,e as rt,g as qs,M as Er,h as qr,i as Or,o as us,j as Ss,p as Zd}from"./ChartPrimitives-B_LDVvTy.js";import{u as eu,t as tu,e as su,a as ut}from"./extract-error-message-B3TERCQ-.js";import{R as fn,C as bn,X as vn,Y as yn,T as jn,L as Gr,A as zs,a as Fr,b as nu,d as _r,e as au}from"./vendor-recharts-D8rt5lKn.js";import{A as iu}from"./AuditHistoryPanel-BCtMrEMF.js";import{a as ru,b as ou}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function Bn(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function lu(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let i=t;i<=s&&(a.push(i),!(a.length>=n));i=cu(i,1));return a}function cu(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const i=a.getUTCFullYear(),r=String(a.getUTCMonth()+1).padStart(2,"0"),o=String(a.getUTCDate()).padStart(2,"0");return`${i}-${r}-${o}`}function du(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function uu(t,s){const n=du(t,s);return n===null?null:Math.round(n*100)}function da(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Bn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Bn(t.prior)} ${s})`:`Flat ${n} (${Bn(t.prior)} ${s})`}const Ur=30;function bi(t){return Math.round(t*10)/10}function mu(t){return t.prior>=Ur&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${bi(t.deltaAbs)} vs ${bi(t.prior)}`}function hu(t,s,n){return t.prior>=Ur&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Bn(Math.round(t.deltaAbs))} ${s} ${n}`}const xu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Br(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Vr(t){return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function Kr(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Br).map(Vr).filter(Boolean)):new Set}function zr(t,s){const n=Br(t).map(Vr).filter(Boolean).filter(a=>!xu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function pu(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function gu(t,s){const n=Kr(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const o=zr(pu(r),n);!o||a.has(o)||(a.add(o),i.push(r))}return i}function fu(t){const s=Kr(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=zr(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}const bu=1e6;function vu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/bu)}const Qr={queryClass:"all"},yu=["all","non-brand","branded"];function ju(t){return typeof t=="string"&&yu.includes(t)}function Nu(t){const s=ju(t.class)?t.class:Qr.queryClass,n=t.scope;if(typeof n!="string"||n==="all"||n.length===0)return{scope:"all",queryClass:s};const a=n.startsWith("group:")?n.slice(6):"";return a?{scope:"group",groupKey:a,queryClass:s}:{scope:"all",queryClass:s}}function wu(t,s){return s===null||t===null?!1:t!==s}function Su(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===Qr.queryClass?void 0:t.queryClass}}const As=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],vi={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Cu={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},ku="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Au(t,s){if(s.unavailable)return{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1};if(s.noRun)return{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1};if(t.snapshotsTotal===0)return s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1};if(t.snapshotsWithAnswerText===0)return{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1};if(!s.hasCompetitors)return{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1};const n=t.projectMentionSnapshots+t.competitorMentionSnapshots;return n===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:`${t.score}`,numeric:!0,detail:`${t.projectMentionSnapshots} of ${n} brand mentions`,showRows:!0}}function Pu({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const i=new Map(t.perCompetitor.map(o=>[o.domain,o.mentionSnapshots])),r=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(o=>({label:o,mentions:i.get(o)??0,isYou:!1}))].sort((o,m)=>m.mentions-o.mentions||(o.label<m.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Je,{text:ku})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:r.map(o=>{const m=o.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${o.isYou?"text-heading font-medium":"text-secondary"}`,children:o.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${o.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${m>0?Math.max(m,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:o.mentions}),e.jsxs("td",{className:"mention-share-share",children:[m.toFixed(1),"%"]})]},o.label)})})]})}function Ru({summary:t,projectLabel:s,competitorDomains:n}){const[a,i]=l.useState("non-brand"),r=l.useId(),o=t.scope==="pooled",m=!o&&t.branded.snapshotsTotal>0,c=m?a:"non-brand",h=o?"pooled":c,p=c==="branded"?t.branded:t.breakdown,u=c==="branded"?t.breakdown:t.branded,v=Au(p,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:u.snapshotsTotal>0}),j=h==="non-brand"?jr[t.tone]:"text-secondary";function b(g){const f=As.findIndex(O=>O.value===c);let k=null;g.key==="ArrowRight"||g.key==="ArrowDown"?k=(f+1)%As.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?k=(f-1+As.length)%As.length:g.key==="Home"?k=0:g.key==="End"&&(k=As.length-1),k!==null&&(g.preventDefault(),i(As[k].value),g.currentTarget.querySelectorAll('[role="radio"]')[k]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:r,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Je,{text:Cu[h]})]}),m?e.jsx("div",{role:"radiogroup","aria-labelledby":r,className:"segmented flex-wrap",onKeyDown:b,children:As.map(g=>{const f=g.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>i(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:vi[h]})]}),v.numeric?e.jsxs("p",{className:`mention-share-value ${j}`,children:[v.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:v.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:vi[h]}),` · ${v.detail}`]}),o&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),v.showRows&&e.jsx(Pu,{breakdown:p,projectLabel:s,competitorDomains:n})]})}function Ma({state:t,label:s}){return e.jsx(oe,{tone:_o(t),children:s??Fo(t)})}function yi({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},i={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((h,p)=>{const u=new Date(h.createdAt).toLocaleDateString();return`${p===r?"Latest run, ":""}${u}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:o}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,p)=>{const u=!!(h.model&&p>0&&n[p-1]?.model&&n[p-1].model!==h.model),v=p===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${u?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${v?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,u?"model changed":null,v?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[m," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function La(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Iu=320;function $u(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function ji(t,s){return s==="citations"?t.citationState:t.visibilityState==="pending"||t.answerMentioned==null&&t.visibilityState==null?"pending":t.visibilityState==="visible"||t.answerMentioned===!0?"cited":"not-cited"}function Ni(t,s){if(s==="mentions")switch(t){case"cited":return"Mentioned";case"not-cited":return"Not Mentioned";case"pending":return"Pending";case"emerging":return"Newly Mentioned";case"lost":return"No Longer Mentioned"}switch(t){case"cited":return"Cited";case"not-cited":return"Not Cited";case"lost":return"Lost";case"emerging":return"Emerging";case"pending":return"Pending"}}function wi(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let o=0;for(let m=t.length-1;m>=0&&t[m].citationState===i;m--)o++;return i==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Tu(t,s){return t.map(n=>Hr(n,s))}function Hr(t,s){return s==="citations"?t:{...t,citationState:ji(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:ji(n,s)}))}}function Si(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",m=r==="cited"||r==="emerging";return i==="lost"||r!==null&&m&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!m&&o?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Mu(t){const s=La(Tu(t,"mentions")),n=La(t);return[Si(s,"mentions"),Si(n,"citations")]}function Lu({signal:t}){const s=t.tone==="positive"?"border-positive-500/25 bg-positive-500/10 text-positive":t.tone==="negative"?"border-negative-500/25 bg-negative-500/10 text-negative":t.tone==="pending"?"border-caution-500/20 bg-caution-500/10 text-caution":"border-mono-700/60 bg-bg-elevated/70 text-secondary";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function Ci({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Mu(t).map(s=>e.jsx(Lu,{signal:s},s.key))})}function Du({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Nr(),[i,r]=l.useState(new Set),[o,m]=l.useState("mentions"),[c,h]=l.useState(n),p=l.useMemo(()=>{const O=new Map;for(const q of t){const A=q.query,d=s?q.location??null:null,y=s?JSON.stringify([A,d]):A,S=O.get(y)??{key:y,phrase:A,location:d,items:[],rawItems:[]};S.items.push(Hr(q,o)),S.rawItems.push(q),O.set(y,S)}return[...O.values()]},[t,o,s]),u=pn({rows:p,getSearchText:$u}),v=u.rows.map(O=>O.key),j=v.length>0&&v.every(O=>i.has(O)),b=O=>{r(q=>{const A=new Set(q);return A.has(O)?A.delete(O):A.add(O),A})},g=o==="mentions"?"mentioned":"cited",f=o==="mentions"?"Mention History":"Citation History",k=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(O=>{const q=new Set(O);for(const A of v)j?q.delete(A):q.add(A);return q})},children:j?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),p.length>0?e.jsx(Hs,{value:u.query,onChange:u.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:f}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:u.rows.map(({key:O,phrase:q,location:A,items:d,rawItems:y})=>{const S=i.has(O),V=d.map($=>$.citationState),K=V.includes("cited")?"cited":V.includes("emerging")?"emerging":V.includes("lost")?"lost":V.every($=>$==="pending")?"pending":"not-cited",w=La(d),T=d.filter($=>$.citationState===Uo.cited||$.citationState==="emerging").length,F=wi(w,o);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>b(O),onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),b(O))},tabIndex:0,role:"button","aria-expanded":S,children:[e.jsx("td",{children:e.jsx(Vd,{size:14,className:`transition-transform duration-150 text-muted ${S?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:q}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:A??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:d.map($=>e.jsx(Js,{provider:$.provider},$.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{state:K,label:Ni(K,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${T} of ${d.length} engines ${k}`,children:[T,"/",d.length]})]})}),e.jsx("td",{children:e.jsx(yi,{history:w})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:F}),e.jsx(Ci,{items:y})]}),e.jsx("td",{})]}),S&&d.map(($,H)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Js,{provider:$.provider})}),e.jsx("td",{children:e.jsx(Ma,{state:$.citationState,label:Ni($.citationState,o)})}),e.jsx("td",{children:e.jsx(yi,{history:$.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:wi($.runHistory,o)}),e.jsx(Ci,{items:[y[H]??$]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:ye=>{ye.stopPropagation(),a($.id)},children:"View"})})]}),c==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Ou,{item:$,onViewFull:()=>a($.id)})})]})]},$.id))]},O)})})]})}),u.totalRows===0&&u.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Es,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",g==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Eu(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(i=>{const r=Vo(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function ki(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function qu(t,s){if(t.length<=s)return{body:t,truncated:!1};const n=t.lastIndexOf(" ",s);return{body:`${t.slice(0,n>s-40?n:s).trimEnd()}…`,truncated:!0}}function Ou({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:i}=qu(t.answerSnippet,Iu),r=Eu(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:Bo(a,r)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${ki(t,o)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[o,ki(t,o)?" · competitor source":""]},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Gu({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const m=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),c=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:c,onClick:i?()=>s(o.domain):void 0,title:i?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:Ko(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:h=>{h.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Rn({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}const Fu=6,en="__other__",Ys="_socialTotal";function _u(t,s=Fu){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const a=[...n.entries()].sort((p,u)=>u[1]!==p[1]?u[1]-p[1]:p[0].localeCompare(u[0])),i=a.slice(0,s),r=new Set(i.map(([p])=>p)),o=Math.max(0,a.length-s),m=new Map;for(const p of t){let u=m.get(p.date);u||(u={date:p.date,[Ys]:0},m.set(p.date,u));const v=r.has(p.source)?p.source:en;u[v]=(u[v]??0)+p.sessions,u[Ys]=(u[Ys]??0)+p.sessions}const c=[...m.values()].sort((p,u)=>String(p.date).localeCompare(String(u.date))),h=i.map(([p])=>p);return o>0&&h.push(en),{data:c,sources:h,otherCount:o}}function Xs(t){return t.replace(/\+/g," ")}function Wr(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ai="_totalSessions",Pi="_organicSessions";function Uu(t,s){const n=new Map;for(const o of s)n.set(o.date,{[Ai]:o.sessions,[Pi]:o.organicSessions});for(const o of t.days){let m=n.get(o.date);m||(m={[Ai]:0,[Pi]:0},n.set(o.date,m));for(const c of o.bySource)m[c.source]=(m[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([o],[m])=>o.localeCompare(m)).map(([o,m])=>({date:o,...m})),i=a.map(o=>o.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const Bu=["7d","30d","90d","all"],js=rt,Da=Ht.textDim,Yr=Ht.textFaint,rn=25;function Vu(t){return Mr(t.landingPage)}const Ku=25,zu=10,ua={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function In(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Xr(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Qu({projectName:t}){const{data:s,isLoading:n,isError:a}=eu(t);if(n)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!J()&&e.jsx(as,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(pe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!J()&&e.jsxs(e.Fragment,{children:[e.jsx(as,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(pe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:tu(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Xr(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:J()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(as,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function Hu({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Qu,{projectName:t}),e.jsx(Wu,{projectName:t})]})}function Wu({projectName:t}){const s=Cs(),[n,a]=l.useState(null),[i,r]=l.useState(null),[o,m]=l.useState(!0),[c,h]=l.useState(!1),[p,u]=l.useState(!1),[v,j]=l.useState(null),[b,g]=l.useState(null),[f,k]=l.useState("sessions"),[O,q]=l.useState("desc"),[A,d]=l.useState("sessions"),[y,S]=l.useState("desc"),[V,K]=l.useState("sessions"),[w,T]=l.useState("desc"),[F,$]=l.useState("sessions"),[H,ye]=l.useState("desc"),[ge,z]=l.useState(ua),[ee,ie]=l.useState([]),[W,B]=l.useState([]),[R,se]=l.useState(!1),[le,de]=l.useState("30d");async function X(G){m(!0),j(null);try{const ke=await s.fetchQuery({...zo({client:U,path:{name:t}}),staleTime:an});if(G.current)return;if(a(ke),!ke.connected){r(null),z(ua),ie([]),B([]),m(!1);return}const fe=le==="all"?void 0:le,he=await s.fetchQuery({...Qo({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).then(Wt=>Wt),Mt=he.windowStart||he.windowEnd?{...he.windowStart?{startDate:he.windowStart}:{},...he.windowEnd?{endDate:he.windowEnd}:{}}:void 0,[ct,Pt,Lt]=await Promise.all([s.fetchQuery({...Ho({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).catch(()=>ua),s.fetchQuery({...Wo({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).catch(()=>[]),s.fetchQuery({...Yo({client:U,path:{name:t},query:Mt}),staleTime:an}).catch(()=>[])]);if(G.current)return;r(he),z(ct),ie(Pt),B(Lt),m(!1)}catch(ke){if(G.current)return;j(ke instanceof Error?ke.message:"Failed to load GA4 data"),m(!1)}}l.useEffect(()=>{const G={current:!1};return X(G),()=>{G.current=!0}},[t,le,s]);async function Ae(){h(!0),j(null),g(null);try{const G=await wr(t);g(`Synced ${G.rowCount.toLocaleString()} page rows, ${G.aiReferralCount.toLocaleString()} AI and ${G.socialReferralCount.toLocaleString()} social referral rows (${G.days} days)`),await ft(s,"ga"),await X({current:!1})}catch(G){j(G instanceof Error?G.message:"Sync failed")}finally{h(!1)}}async function _(){u(!0),j(null),g(null);try{await Xo(t),await ft(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),g("GA4 disconnected")}catch(G){j(G instanceof Error?G.message:"Disconnect failed")}finally{u(!1)}}function ae(G){Pe.setPage(1),f===G?q(ke=>ke==="desc"?"asc":"desc"):(k(G),q("desc"))}function Ne(G){A===G?S(ke=>ke==="desc"?"asc":"desc"):(d(G),S("desc"))}function Le(G){V===G?T(ke=>ke==="desc"?"asc":"desc"):(K(G),T("desc"))}const Fe=l.useMemo(()=>i?.topPages?[...i.topPages].sort((G,ke)=>{const fe=G[f],he=ke[f];return typeof fe=="string"&&typeof he=="string"?O==="asc"?fe.localeCompare(he):he.localeCompare(fe):O==="asc"?fe-he:he-fe}):[],[i?.topPages,f,O]),Pe=pn({rows:Fe,getSearchText:G=>Mr(G.landingPage),pageSize:zu}),Qe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((G,ke)=>{const fe=G[A],he=ke[A];return typeof fe=="string"&&typeof he=="string"?y==="asc"?fe.localeCompare(he):he.localeCompare(fe):y==="asc"?fe-he:he-fe}):[],[i?.aiReferrals,A,y]),ue=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((G,ke)=>{const fe=G[F],he=ke[F];return typeof fe=="string"&&typeof he=="string"?H==="asc"?fe.localeCompare(he):he.localeCompare(fe):H==="asc"?fe-he:he-fe}):[],[i?.aiReferralLandingPages,F,H]),we=pn({rows:ue,getSearchText:Vu,pageSize:Ku}),Ze=we.totalRows>0?`${we.totalRows.toLocaleString()} ${we.hasQuery?we.totalRows===1?"match":"matches":we.totalRows===1?"row":"rows"}`:we.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function _e(G){we.setPage(1),F===G?ye(ke=>ke==="desc"?"asc":"desc"):($(G),ye("desc"))}const He=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((G,ke)=>{const fe=G[V],he=ke[V];return typeof fe=="string"&&typeof he=="string"?w==="asc"?fe.localeCompare(he):he.localeCompare(fe):w==="asc"?fe-he:he-fe}):[],[i?.socialReferrals,V,w]),{socialChartData:$e,socialChartSources:Ce,socialOtherCount:E}=l.useMemo(()=>{const G=_u(W);return{socialChartData:G.data,socialChartSources:G.sources,socialOtherCount:G.otherCount}},[W]),{chartData:M,chartSources:L,dateRange:je}=l.useMemo(()=>{const G=Uu(ge,ee);return{chartData:G.data,chartSources:G.sources,dateRange:G.dateRange}},[ge,ee]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return J()?e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Yu,{projectName:t,onConnected:()=>{(async()=>(await ft(s,"ga"),await X({current:!1})))()}});const qe=i?.organicSharePctDisplay??"0%",Y=i?.channelBreakdown?.organic.sharePctDisplay??qe,Be=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,mt=i?.aiSessionsDeduped??0,ot=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,De=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Oe=i?.paidAiSessionsBySession??0,xt=i?.paidAiSharePctBySessionDisplay??"0%",We=i?new Set(i.aiReferrals.map(G=>G.source.toLowerCase())).size:0,Ve=Qe[0]??null,Te=i?.totalDirectSessions??0,jt=i?.directSharePctDisplay??"0%",Tt=i?.channelBreakdown?.direct.sessions??Te,Ue=i?.channelBreakdown?.direct.sharePctDisplay??jt,Ge=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,bt=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ke=i?.socialSessions??0,Nt=i?.socialSharePctDisplay??"0%",kt=i?.channelBreakdown?.social.sessions??Ke,vt=i?.channelBreakdown?.social.sharePctDisplay??Nt,At=i?new Set(i.socialReferrals.map(G=>G.source.toLowerCase())).size:0,lt=He[0]??null;return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:v}),b&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:b}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!J()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:c,onClick:Me(Ae),children:[e.jsx(Qn,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),c?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:p,onClick:Me(_),children:[e.jsx(Kd,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Je,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:Bu.map(G=>e.jsx("button",{type:"button","aria-pressed":le===G,className:`segmented-option ${le===G?"segmented-option-active":""}`,onClick:()=>de(G),children:G==="all"?"All":G},G))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(ma,{value:In(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(ma,{value:In(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${qe} of total`,tone:"positive"}),e.jsx(ma,{value:i.totalUsers===null?"—":In(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!J()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:c,onClick:Me(Ae),children:[e.jsx(Qn,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Je,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),je&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(je.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(je.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),M.length>0&&e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:L.length>0?"AI vs. total sessions":"All sessions (baseline)"}),L.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),L.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:M,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(G,ke)=>{const fe=typeof G=="number"?G.toLocaleString():String(G??0),he=String(ke??"");return he==="_totalSessions"?[fe,"Total Sessions"]:he==="_organicSessions"?[fe,"Organic Sessions"]:[fe,he]}}),e.jsx(Gr,{wrapperStyle:{fontSize:11,color:Ht.text},formatter:G=>G==="_totalSessions"?"Total Sessions":G==="_organicSessions"?"Organic Sessions":G}),e.jsx(zs,{type:"monotone",dataKey:"_totalSessions",stroke:Ht.textFaint,fill:Ht.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),L.map((G,ke)=>e.jsx(zs,{type:"monotone",dataKey:G,stackId:"ai",stroke:js[ke%js.length],fill:js[ke%js.length],fillOpacity:.4,strokeWidth:1.5},G))]})})})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Jt,{label:"Organic",value:Y,hint:`${Be.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(Jt,{label:"Social",value:vt,hint:`${kt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(Jt,{label:"Direct",value:Ue,hint:`${Tt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(Jt,{label:"Visitors from AI (at least)",value:De,hint:Oe>0?`${ot.toLocaleString()} sessions · ${Oe.toLocaleString()} paid`:`${ot.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(Jt,{label:"Other channels",value:bt,hint:`${Ge.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),Ve&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:Ve.source})," via ",Ve.medium,", accounting for ",Ve.sessions.toLocaleString()," sessions.",Oe>0&&e.jsxs("span",{children:[" Paid AI: ",Oe.toLocaleString()," sessions (",xt,")."]})]})]}),e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${We} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Source",sortKey:"source",current:A,dir:y,onSort:Ne,align:"left"}),e.jsx(_t,{label:"Medium",sortKey:"medium",current:A,dir:y,onSort:Ne,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:A,dir:y,onSort:Ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Qe.map(G=>e.jsx(Ju,{referral:G,totalSessions:mt},`${G.source}:${G.medium}:${G.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:Ze})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:we.query,onChange:we.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),we.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Landing Page",sortKey:"landingPage",current:F,dir:H,onSort:_e,align:"left"}),e.jsx(_t,{label:"Source",sortKey:"source",current:F,dir:H,onSort:_e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:F,dir:H,onSort:_e,align:"right"})]})}),e.jsx("tbody",{children:we.rows.map(G=>e.jsx(Zu,{row:G},`${G.landingPage}:${G.source}:${G.medium}:${G.sourceDimension}`))})]})}),e.jsx(Es,{page:we.page,pageSize:we.pageSize,visibleRows:we.rows.length,totalRows:we.totalRows,onPageChange:we.setPage,itemLabel:we.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>we.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Je,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),$e.length>0&&e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),E>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ce.length-1," sources · ",E," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:$e,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(G,ke)=>{const fe=typeof G=="number"?G.toLocaleString():String(G??0),he=String(ke??"");if(he===Ys)return[fe,"Total Social"];if(he===en){const Mt=`Other (${E} source${E===1?"":"s"})`;return[fe,Mt]}return[fe,Xs(he)]}}),e.jsx(zs,{type:"monotone",dataKey:Ys,stroke:Yr,fill:Ht.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ce.map((G,ke)=>{const he=G===en?Da:js[ke%js.length];return e.jsx(zs,{type:"monotone",dataKey:G,stackId:"social",stroke:he,fill:he,fillOpacity:.4,strokeWidth:1.5},G)})]})})}),e.jsx(tm,{sources:Ce,otherCount:E})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Jt,{label:"Social Sessions",value:In(Ke),hint:`${Ke.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Jt,{label:"Share of Traffic",value:Nt,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Jt,{label:"Platforms",value:String(At),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),lt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${lt.source} via ${lt.medium}`,children:Wr(Xs(lt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:lt.medium,children:["via ",Xs(lt.medium)," · ",lt.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Jt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Jt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Jt,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),e.jsxs(pe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?He.length>rn&&!R?`Top ${rn} of ${He.length}`:`${He.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Source",sortKey:"source",current:V,dir:w,onSort:Le,align:"left"}),e.jsx(_t,{label:"Medium",sortKey:"medium",current:V,dir:w,onSort:Le,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:V,dir:w,onSort:Le,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(_t,{label:"Users",sortKey:"users",current:V,dir:w,onSort:Le,align:"right"})]})}),e.jsx("tbody",{children:(R?He:He.slice(0,rn)).map(G=>e.jsx(em,{referral:G,totalSessions:Ke},`${G.source}:${G.medium}:${G.channelGroup}`))})]})}),He.length>rn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>se(G=>!G),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:R?`Show top ${rn}`:`Show all ${He.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Je,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Hs,{value:Pe.query,onChange:Pe.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(_t,{label:"Landing Page",sortKey:"landingPage",current:f,dir:O,onSort:ae,align:"left"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:f,dir:O,onSort:ae,align:"right"}),e.jsx(_t,{label:"Organic",sortKey:"organicSessions",current:f,dir:O,onSort:ae,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Pe.rows.map(G=>e.jsx(Xu,{page:G},G.landingPage))})]})}),Pe.totalRows===0&&Pe.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Es,{page:Pe.page,pageSize:Pe.pageSize,visibleRows:Pe.rows.length,totalRows:Pe.totalRows,onPageChange:Pe.setPage,itemLabel:Pe.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Xr(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Yu({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[i,r]=l.useState(null),[o,m]=l.useState(null),[c,h]=l.useState(!1),[p,u]=l.useState(null),v=l.useRef(null),j=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),r(f.name);const k=new FileReader;k.onload=()=>{const O=k.result;try{const q=JSON.parse(O);if(!q.client_email||!q.private_key){u("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),m(null);return}m(O)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},k.onerror=()=>{u("Failed to read file."),m(null)},k.readAsText(f)},[]);async function b(){if(u(null),!n.trim()){u("Property ID is required.");return}if(!o){u("Please upload a service account key file.");return}h(!0);try{await Jo(t,{propertyId:n.trim(),keyJson:o});try{await wr(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(pe,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),p&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:p}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:g=>a(g.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:v,type:"file",accept:".json,application/json",onChange:j,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>v.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(zd,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(P,{variant:"default",size:"sm",disabled:c||!n.trim()||!o,onClick:Me(b),children:c?"Connecting & syncing…":"Connect GA4"})]})}function _t({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const o=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Jr={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function ma({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${Jr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Jt({value:t,label:s,hint:n,tone:a,tooltip:i}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,i&&e.jsx(Je,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Jr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Xu({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]})]})}const Zr={session:"Session",first_user:"First Visit",manual_utm:"UTM"},eo={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function Ju({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Zr[t.sourceDimension]??t.sourceDimension,i=eo[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Zu({row:t}){const s=Zr[t.sourceDimension]??t.sourceDimension,n=eo[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(Un,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function em({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Xs(t.source),r=Xs(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function tm({sources:t,otherCount:s}){const n=[{key:Ys,color:Yr,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===en)n.push({key:en,color:Da,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Xs(i);n.push({key:i,color:js[a%js.length]??Da,label:Wr(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function to({windows:t,value:s,onChange:n,label:a,formatOption:i,disabled:r=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(o=>e.jsx("button",{type:"button","aria-pressed":s===o,disabled:r,className:`segmented-option ${s===o?"segmented-option-active":""}`,onClick:()=>n(o),children:i?i(o):o},o))})}function sm(t){const s=t.details;if(t.code!=="FORBIDDEN"||!s||s.reason!=="gsc-api-disabled")return null;const n=typeof s.projectNumber=="string"?s.projectNumber:void 0;return{title:"Enable the Search Console API",message:`Your Google Cloud project${n?` (${n})`:""} hasn't enabled the Search Console API. Enable the Search Console API and the Indexing API, wait ~2–5 minutes, then retry.`,enableUrl:typeof s.enableUrl=="string"?s.enableUrl:void 0,indexingApiUrl:typeof s.indexingApiUrl=="string"?s.indexingApiUrl:void 0,projectNumber:n}}const nm=["7d","30d","90d","all"],$n=500,Ri=[{key:"clicks",label:"Clicks",color:rt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:rt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:qs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:rt[2],inverted:!0,format:t=>t.toFixed(1)}],bs=25,am="canonry:google-oauth-complete",im=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function rm(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const i=t.change[s];if(i===null||!Number.isFinite(i)){const c=t.prior[s],h=t.trailing[s];return c!==null&&h!==null&&c<=0&&h>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(i===0)return`→ no change vs prior ${a}d`;const r=Math.abs(i*100),o=r<.1?"<0.1%":`${im.format(r)}%`;return`${(n?i<0:i>0)?"↑":"↓"} ${o} vs prior ${a}d`}function Ii(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function $i(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function Ti(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function om({projectName:t,refreshNonce:s}){const n=Cs(),[a,i]=l.useState(!1),[r,o]=l.useState([]),[m,c]=l.useState([]),[h,p]=l.useState([]),[u,v]=l.useState(null),[j,b]=l.useState([]),[g,f]=l.useState([]),[k,O]=l.useState(null),[q,A]=l.useState(""),[d,y]=l.useState(""),[S,V]=l.useState("30"),[K,w]=l.useState(!1),[T,F]=l.useState("30d"),[$,H]=l.useState(["clicks","impressions"]),[ye,ge]=l.useState(!0),[z,ee]=l.useState(null),[ie,W]=l.useState(0),[B,R]=l.useState({startDate:"",endDate:"",query:"",page:""}),[se,le]=l.useState(0),[de,X]=l.useState(!1),[Ae,_]=l.useState(0),[ae,Ne]=l.useState(!1),[Le,Fe]=l.useState(""),[Pe,Qe]=l.useState(!0),[ue,we]=l.useState(!1),[Ze,_e]=l.useState(!1),[He,$e]=l.useState(!1),[Ce,E]=l.useState(!1),[M,L]=l.useState(!1),[je,qe]=l.useState(!1),[Y,Be]=l.useState(null),[mt,ot]=l.useState(!1),[De,Oe]=l.useState(!1),[xt,We]=l.useState(null),[Ve,Te]=l.useState(null),[jt,Tt]=l.useState([]),[Ue,Ge]=l.useState(new Set),[bt,Ke]=l.useState({}),[Nt,kt]=l.useState(new Set),[vt,At]=l.useState(""),[lt,G]=l.useState(null),[ke,fe]=l.useState(""),[he,Mt]=l.useState(!1),[ct,Pt]=l.useState(!1),[Lt,Wt]=l.useState(!1),[Dt,is]=l.useState(!1),[nt,ms]=l.useState("indexed"),[wt,hs]=l.useState(null),Ot=!!(B.query.trim()||B.page.trim()||wt),Yt=wt!==null,Bt=l.useMemo(()=>{if(!wt)return h;const{key:x,dir:D}=wt;return[...h].sort((Z,ce)=>{const ze=x===Ls.CTR?Number.isFinite(Z.ctr)?Z.ctr:0:Z[x],Xe=x===Ls.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[x];return D==="asc"?ze-Xe:Xe-ze})},[h,wt]),et=pn({rows:Bt,pageSize:os}),xs=ae?et.rows:Bt,Gt=pn({rows:(xt??[]).filter(x=>x.path.toLowerCase().includes(vt.trim().toLowerCase())),pageSize:os}),[St,ps]=l.useState([]),[dt,Zt]=l.useState(null),[C,be]=l.useState(1),ve=l.useMemo(()=>{if(St.length<2)return null;const x=St[St.length-1],D=St[St.length-2];return{indexed:x.indexed-D.indexed,notIndexed:x.notIndexed-D.notIndexed}},[St]);l.useEffect(()=>{be(1)},[Y,nt,dt]);const I=l.useMemo(()=>dt?(Y?.reasonGroups??[]).find(x=>x.reason===dt):void 0,[Y,dt]),Q=l.useMemo(()=>Y?nt==="indexed"?Y.indexed:nt==="deindexed"?Y.deindexed:nt==="notIndexed"?dt?I?.urls??[]:(Y.reasonGroups??[]).length===0?Y.notIndexed:[]:[]:[],[Y,nt,dt,I]),me=Math.max(1,Math.ceil(Q.length/bs)),te=Math.min(Math.max(1,C),me),ne=(te-1)*bs,Ee=l.useMemo(()=>Y?.indexed.slice(ne,ne+bs)??[],[Y,ne]),es=l.useMemo(()=>Y?.notIndexed.slice(ne,ne+bs)??[],[Y,ne]),pt=l.useMemo(()=>Y?.deindexed.slice(ne,ne+bs)??[],[Y,ne]),Fs=l.useMemo(()=>(I?.urls??[]).slice(ne,ne+bs),[I,ne]),[N,re]=l.useState(!1),[at,Re]=l.useState(null),[gt,rs]=l.useState(null),[Vt,Xt]=l.useState(null);function ko(x,D){const Z=su(x),ce=sm(Z);ce?(rs(ce),Re(null)):(rs(null),Re(Z.message||D))}const Ft=r.find(x=>x.connectionType==="gsc"),ks=(Ft?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),ta=jt.length>0?jt:(xt??[]).map(x=>x.path),si=ta.filter(x=>xt?.some(D=>D.path===x&&D.isSitemapsIndex)).length,Ao=si===1?"Resubmit sitemap index":si>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Po=h.length>0||j.length>0||g.length>0,sa=Zo(),na=el();async function ni(x,D=!1){if(!x){c([]),A("");return}_e(!0);try{const{sites:Z}=await n.fetchQuery({...xl({client:U,path:{name:t}}),staleTime:D?0:$t});c(Z),A(x.propertyId??Z[0]?.siteUrl??""),rs(null)}catch(Z){c([]),ko(Z,"Failed to load Search Console properties")}finally{_e(!1)}}async function sn(x){E(!0);const D=x??se;try{const Z=Ot?$n:os,ce=Ot?0:D,ze={limit:String(Z)};B.startDate&&(ze.startDate=B.startDate),B.endDate&&(ze.endDate=B.endDate),B.query&&(ze.query=B.query),B.page&&(ze.page=B.page),ce>0&&(ze.offset=String(ce)),T&&T!=="all"&&!B.startDate&&(ze.window=T);const Xe=await n.fetchQuery({...nl({client:U,path:{name:t},query:ze}),staleTime:$t}),tt=Xe.rows;Ot?(X(!1),p(tt),_(tt.length),Ne(!0)):(X(ce+tt.length<Xe.totalMatching),p(tt),_(0),Ne(!1))}catch(Z){p([]),X(!1),_(0),Re(Z instanceof Error?Z.message:"Failed to load GSC performance data")}finally{E(!1)}}async function aa(){try{const x={};B.startDate&&(x.startDate=B.startDate),B.endDate&&(x.endDate=B.endDate),T&&T!=="all"&&!B.startDate&&(x.window=T);const D=await n.fetchQuery({...sl({client:U,path:{name:t},query:x}),staleTime:$t});v(D)}catch{v(null)}}async function kn(x=!1){L(!0);try{const D=Le.trim()||void 0,Z={limit:"20"};D&&(Z.url=D);const[ce,ze]=await Promise.all([n.fetchQuery({...ml({client:U,path:{name:t},query:Z}),staleTime:x?0:$t}),n.fetchQuery({...hl({client:U,path:{name:t}}),staleTime:x?0:$t})]);b(ce),f(ze)}catch(D){b([]),f([]),Re(D instanceof Error?D.message:"Failed to load GSC inspection history")}finally{L(!1)}}async function ai(x=!1){ot(!0);try{const[D,Z]=await Promise.all([n.fetchQuery({...rl({client:U,path:{name:t}}),staleTime:x?0:$t}),n.fetchQuery({...ol({client:U,path:{name:t}}),staleTime:x?0:$t}).catch(()=>[])]);Be(D),ps(Z)}catch(D){Be(null),ps([]),Re(D instanceof Error?D.message:"Failed to load coverage data")}finally{ot(!1)}}async function ii(x){re(!0),Re(null);try{const D=await xi(t,{urls:x}),{succeeded:Z,failed:ce,total:ze}=D.summary;Se({title:"Indexing requested",detail:ce===0?`${Z} URL${Z!==1?"s":""} submitted for indexing.`:`${Z}/${ze} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to request indexing")}finally{re(!1)}}async function Ro(){re(!0),Re(null);try{const x=await xi(t,{urls:[],allUnindexed:!0}),{succeeded:D,failed:Z,total:ce}=x.summary;Se({title:"Indexing requested",detail:Z===0?`${D} unindexed URL${D!==1?"s":""} submitted for indexing.`:`${D}/${ce} submitted successfully, ${Z} failed.`,tone:Z===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(x){Re(x instanceof Error?x.message:"Failed to request indexing")}finally{re(!1)}}async function ia(){Oe(!0),Re(null);try{const x=await oa(t);n.setQueryData(ll({client:U,path:{name:t}}),x),We(x.sitemaps),Te(x.summary),Tt(x.preferredSubmissionUrls),Ge(new Set),Ke({}),x.sitemaps.length===0&&Xt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(x){Re(x instanceof Error?x.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function Io(x){const D=Ue.has(x);if(Ge(Z=>{const ce=new Set(Z);return D?ce.delete(x):ce.add(x),ce}),!(D||bt[x])){kt(Z=>new Set(Z).add(x));try{const Z=await oa(t,x);Ke(ce=>({...ce,[x]:Z.sitemaps}))}catch(Z){Re(Z instanceof Error?Z.message:"Failed to load sitemap files")}finally{kt(Z=>{const ce=new Set(Z);return ce.delete(x),ce})}}}async function _s(x){if(!ks||x.length===0)return;const D=[...new Set(x)];Pt(!0),Re(null),G({completed:0,total:D.length});let Z=0,ce=0,ze=0,Xe=null;try{for(let yt=0;yt<D.length;yt+=50){const st=D.slice(yt,yt+50);try{const xe=await cl(t,st);Z+=xe.summary.accepted,ce+=xe.summary.failed,ze+=st.length,G({completed:ze,total:D.length})}catch(xe){ze+=st.length;const gs=st.length,nn=D.length-ze,An=xe instanceof Error?xe.message:"The batch request failed",fs=`${Z} accepted, ${ce} failed, ${gs} unconfirmed, ${nn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Xe=`Sitemap submission stopped after a batch request failed. ${fs} ${An}`,Re(Xe),Se({title:"Sitemap resubmission partially completed",detail:fs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const tt=D.length;Se({title:ce===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ce===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${Z}/${tt} sitemap submissions; ${ce} failed. Indexing is not guaranteed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),fe("")}catch(tt){Re(tt instanceof Error?tt.message:"Failed to submit sitemap to Google")}finally{Pt(!1),G(null),await ia(),Xe&&Re(Xe)}}async function $o(){Pt(!0);const x=xt??[];try{const D=x.filter(ce=>ce.isSitemapsIndex),Z=[];for(let ce=0;ce<D.length;ce+=4)(await Promise.all(D.slice(ce,ce+4).map(async Xe=>{const tt=bt[Xe.path];if(tt)return tt;const yt=await oa(t,Xe.path);return Ke(st=>({...st,[Xe.path]:yt.sitemaps})),yt.sitemaps}))).forEach((Xe,tt)=>{Z.push(...Xe.length>0?Xe.map(yt=>yt.path):[D[ce+tt].path])});await _s([...x.filter(ce=>!ce.isSitemapsIndex).map(ce=>ce.path),...Z])}catch(D){Re(D instanceof Error?D.message:"Failed to load sitemap files"),Pt(!1)}}async function ri(x){Mt(!0),Re(null);try{await dl(t,"gsc",x),await ft(n,"google"),o(D=>D.map(Z=>Z.connectionType==="gsc"?{...Z,sitemapUrl:x}:Z)),Se({title:"Default sitemap updated",detail:x,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to set the default sitemap")}finally{Mt(!1)}}async function oi(x){try{await na.mutateAsync({projectName:t,projectLabel:t,opts:x?{sitemapUrl:x}:void 0})}catch{}}async function li(){Qe(!0),Re(null);try{const[x,D]=await Promise.all([Sr().catch(()=>null),n.fetchQuery({...Ba({client:U,path:{name:t}}),staleTime:$t}).catch(()=>[])]);i(!!x?.google?.configured),o(D);const Z=D.find(ce=>ce.connectionType==="gsc");await Promise.all([ni(Z),sn(),aa(),kn(),ai(),Z?.propertyId?ia():Promise.resolve()])}finally{Qe(!1)}}l.useEffect(()=>{li()},[t,s]),l.useEffect(()=>{le(0),ee(null),R(x=>x.startDate||x.endDate?{...x,startDate:"",endDate:""}:x),W(x=>x+1),aa()},[T]);const ci=l.useRef(!1);l.useEffect(()=>{if(!ci.current){ci.current=!0;return}le(0),et.setPage(1),sn(0)},[ie]);function ra(x){const D=z===x?null:x;ee(D),R(Z=>({...Z,startDate:D??"",endDate:D??""})),W(Z=>Z+1)}const di=l.useRef(!1);l.useEffect(()=>{if(!di.current){di.current=!0;return}le(0),sn(0)},[Yt]);async function ui(){if(!a){Re("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),Re(null),Xt(null);try{let x=function(xe){if(xe.source!==ce||xe.origin!==ze||!xe.data||typeof xe.data!="object")return;const gs=xe.data;gs.type!==am||gs.connectionType!=="gsc"||st(!0)};const{authUrl:D,redirectUri:Z}=await il(t,"gsc");if(!D.startsWith("https://accounts.google.com/")){Re("Unexpected OAuth redirect URL. Please try again.");return}const ce=window.open(D,"_blank","width=600,height=700");if(!ce){window.location.assign(D);return}const ze=Z?new URL(Z).origin:window.location.origin;let Xe=!1,tt=null;const yt=()=>{tt!==null&&window.clearInterval(tt),window.removeEventListener("message",x)},st=async xe=>{if(!Xe){Xe=!0,yt(),Xt(xe?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await ft(n,"google"),await li()}finally{Xt(null)}}};window.addEventListener("message",x),Xt("Finish the Google consent flow in the popup. This page will refresh automatically."),tt=window.setInterval(()=>{ce.closed&&st(!1)},1e3)}catch(x){Re(x instanceof Error?x.message:"Failed to start OAuth flow")}finally{we(!1)}}async function To(){Re(null),Xt(null);try{await al(t,"gsc"),await ft(n,"google"),o(x=>x.filter(D=>D.connectionType!=="gsc")),c([]),A("")}catch(x){Re(x instanceof Error?x.message:"Failed to disconnect")}}async function Mo(){if(q){$e(!0),Re(null);try{await pl(t,"gsc",q),await ft(n,"google"),o(x=>x.map(D=>D.connectionType==="gsc"?{...D,propertyId:q}:D)),Se({title:"GSC property updated",detail:`${t} is now linked to ${q}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(x){Re(x instanceof Error?x.message:"Failed to save GSC property")}finally{$e(!1)}}}async function Lo(){Re(null),Xt(null);try{await sa.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:K||void 0}}),await ft(n,"gsc")}catch{}}async function mi(){if(d.trim()){qe(!0),Re(null),Xt(null);try{const x=await ul(t,d.trim());await ft(n,"gsc"),O(x),y(""),await kn()}catch(x){Re(x instanceof Error?x.message:"Failed to inspect URL")}finally{qe(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),gt&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:gt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:gt.message}),(Ts(gt.enableUrl)||Ts(gt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ts(gt.enableUrl)&&e.jsx("a",{href:Ts(gt.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Ts(gt.indexingApiUrl)&&e.jsx("a",{href:Ts(gt.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>rs(null),children:"×"})]})}),at&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[at,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Re(null),children:"×"})]}),Vt&&e.jsxs("div",{className:"mb-3 rounded-lg border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-sm text-positive",children:[Vt,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Xt(null),children:"×"})]}),Pe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ft?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:Ft.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",Y?.lastInspectedAt?qt(Y.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Me(To),children:"Disconnect"})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ue,onClick:Me(ui),children:ue?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(as,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),(Ft||Po)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Je,{text:`Tile percentages compare the trailing half of the selected window with the prior equal-length half. The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${$n.toLocaleString()} matching rows while the table shows ${os} per page.`})]}),u?.window?.startDate&&u.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[u.window.startDate," to ",u.window.endDate,(u.window.daysSinceLatestData??0)>0&&` · latest data ${u.window.daysSinceLatestData} day${u.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(to,{windows:nm,value:T,onChange:x=>{F(x),le(0),et.setPage(1)},label:"Search Console time period",formatOption:x=>x==="all"?"All":x}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Ce,onClick:()=>{le(0),et.setPage(1),sn(0),aa()},children:Ce?"Loading…":"Apply filters"})]})]}),u&&u.daily.length>0&&(()=>{const{totals:x,daily:D,trends:Z,periodComparison:ce}=u,Xe=Ri.filter(xe=>$.includes(xe.key)).map(xe=>({dataKey:xe.key,label:xe.label,color:xe.color,axisId:xe.key,inverted:xe.inverted,formatValue:xe.format,trend:ye?Z?.[xe.key]??null:null})),tt=xe=>x[xe]??null,yt=new Map(D.map(xe=>[xe.date,xe])),st=D.length===0?[]:lu(D[0].date,D[D.length-1].date).map(xe=>yt.get(xe)??{date:xe});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Ri.map(xe=>{const gs=$.includes(xe.key),nn=tt(xe.key),An=nn===null;return e.jsxs("button",{type:"button","aria-pressed":gs,disabled:An,className:`rounded-md border px-3 py-2 text-left transition-colors ${gs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${An?"cursor-not-allowed opacity-50":""}`,onClick:()=>{H(fs=>fs.includes(xe.key)?fs.length===1?fs:fs.filter(Do=>Do!==xe.key):[...fs,xe.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:gs?xe.color:"transparent",border:`1px solid ${xe.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:xe.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:nn===null?"—":xe.format(nn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:rm(ce,xe.key,xe.inverted)})]},xe.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:ye,onChange:xe=>ge(xe.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Er,{data:st,xKey:"date",series:Xe,xTickFormatter:gn,labelFormatter:Ut,onSelectX:ra,selectedX:z})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:D.map(xe=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":z===xe.date,onClick:()=>ra(xe.date),children:[Ut(xe.date),": ",xe.clicks," clicks, ",xe.impressions," impressions"]},xe.date))}),z&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ut(z)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ra(z),children:["Show all ",x.days," days"]})]}),x.position!==null&&(x.positionDays??x.days)<x.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",x.positionDays," of ",x.days," days. The rest have no property-level position recorded."]}),(x.position===null||x.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:B.startDate,onChange:x=>R(D=>({...D,startDate:x.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:B.endDate,onChange:x=>R(D=>({...D,endDate:x.target.value}))}),e.jsx(Hs,{value:B.query,onChange:x=>R(D=>({...D,query:x})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Hs,{value:B.page,onChange:x=>R(D=>({...D,page:x})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(Ls).map(x=>e.jsx("th",{className:"text-right","aria-sort":wt?.key===x?wt.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{et.setPage(1),hs(D=>D?.key===x?D.dir==="desc"?{key:x,dir:"asc"}:null:{key:x,dir:"desc"})},children:[tl[x],wt?.key===x?wt.dir==="desc"?" ↓":" ↑":""]})},x))]})}),e.jsx("tbody",{children:xs.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:x.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Un,{value:x.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(x.ctr)?x.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.position.toFixed(1)})]},`${x.date}:${x.query}:${x.page}:${D}`))})]})}),e.jsx(Es,{page:ae?et.page:Math.floor(se/os)+1,pageSize:os,visibleRows:xs.length,totalRows:ae?Ae:void 0,hasNextPage:ae?void 0:de,disabled:Ce,itemLabel:ae?"matches":"rows",onPageChange:x=>{if(ae){et.setPage(x);return}const D=(x-1)*os;le(D),sn(D)}}),ae&&Ae>=$n?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",$n.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Je,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Y&&Y.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:N,onClick:()=>{Ro()},children:N?"Requesting…":`Request indexing (${Y.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:mt,onClick:()=>{ai(!0)},children:mt?"Loading…":"Reload saved coverage"})]})]}),Y&&Y.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const x=Y.summary.indexed+Y.summary.notIndexed,D=x>0?Y.summary.indexed/x:0,Z=x>0?Y.summary.notIndexed/x:0,ce=54,ze=2*Math.PI*ce,Xe=ze*(1-D),tt=ze*Z,yt=ze*D;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Ht.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:qs.positiveDeep,strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Xe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),Y.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Ht.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${ze-tt}`,strokeDashoffset:-yt,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(D*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(Y.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(Y.reasonGroups??[]).length," ",(Y.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),Y.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:Y.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(x=>{const D=x==="indexed"?Y.indexed.length:x==="notIndexed"?Y.notIndexed.length:Y.deindexed.length,Z=x==="indexed"?"Indexed":x==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":nt===x,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${nt===x?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{ms(x),Zt(null)},children:[Z," (",D,")"]},x)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[nt==="indexed"&&Y.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:Ee.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.crawlTime?x.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.isMobileFriendly===!0?"Yes":x.isMobileFriendly===!1?"No":"—"})]},x.id))})]}),nt==="notIndexed"&&!dt&&(Y.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(Y.reasonGroups??[]).map(x=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>Zt(x.reason),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),Zt(x.reason))},tabIndex:0,role:"button","aria-label":`View ${x.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:x.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.count})]},x.reason))})]}),nt==="notIndexed"&&!dt&&(Y.reasonGroups??[]).length===0&&Y.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:es.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"})]},x.id))})]}),nt==="notIndexed"&&dt&&(()=>{const x=(Y.reasonGroups??[]).find(D=>D.reason===dt);return x?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>Zt(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:x.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[x.count," affected page",x.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:N,onClick:()=>{ii(x.urls.map(D=>D.url))},children:N?"Requesting…":`Request indexing (${x.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Fs.map(D=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:D.url}),e.jsx("td",{className:"text-secondary",children:D.crawlTime?D.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:N,onClick:()=>{ii([D.url])},title:"Request indexing",children:"Index"})})]},D.id))})]})]}):null})(),nt==="deindexed"&&Y.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:pt.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState}),e.jsx("td",{className:"text-secondary",children:x.currentState}),e.jsx("td",{className:"text-secondary",children:x.transitionDate.split("T")[0]})]},`${x.url}-${D}`))})]}),(nt==="indexed"&&Y.indexed.length===0||nt==="notIndexed"&&!dt&&Y.notIndexed.length===0||nt==="deindexed"&&Y.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Es,{page:te,pageSize:bs,visibleRows:Math.min(bs,Q.length-ne),totalRows:Q.length,onPageChange:be,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Dt,onClick:()=>is(x=>!x),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Dt?"Hide snapshots":St.length>0?`View ${St.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",Y.summary.indexed.toLocaleString()," indexed, ",Y.summary.notIndexed.toLocaleString()," not indexed.",ve&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ve.indexed>=0?"+":"",ve.indexed.toLocaleString()," indexed, ",ve.notIndexed>=0?"+":"",ve.notIndexed.toLocaleString()," not indexed."]})]}),Dt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:St.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:St.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.notIndexed.toLocaleString()})]},x.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:mt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Je,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:De||!Ft?.propertyId,onClick:()=>{ia()},children:De?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:ke,onChange:x=>fe(x.target.value),onKeyDown:x=>x.key==="Enter"&&void _s([ke.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!ks||ct||!ke.trim(),onClick:()=>{_s([ke.trim()])},children:ct?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ks||ct||ta.length===0,onClick:()=>{_s(ta)},children:ct?"Resubmitting…":Ao}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ks||ct||!xt?.length,onClick:()=>{$o()},children:"Resubmit all files"}),Ve&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ve.indexes," index",Ve.indexes===1?"":"es",", ",Ve.files," file",Ve.files===1?"":"s"]}),lt&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",lt.completed,"/",lt.total]})]}),!ks&&Ft&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Me(ui),children:"Reconnect"})]}),xt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:xt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:vt,onChange:x=>{At(x),Gt.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Gt.rows.flatMap(x=>{const D=Ii(x),Z=$i(x),ce=Ti(x),ze=bt[x.path]??[],Xe=Ue.has(x.path),tt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Un,{value:x.path})}),e.jsx("td",{className:"text-secondary",children:x.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Xe,"aria-label":`${Xe?"Collapse":"Expand"} files in ${x.path}`,onClick:()=>{Io(x.path)},children:Nt.has(x.path)?"Loading…":`${Xe?"▾":"▸"} Index${bt[x.path]?` (${ze.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ce}),e.jsx("td",{className:"text-secondary",children:x.lastSubmitted?x.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.lastDownloaded?x.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:D.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:Z||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!ks||ct,onClick:()=>{_s([x.path])},children:x.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Ft?.sitemapUrl===x.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:he,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ri(x.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:na.isPending,onClick:()=>{oi(x.path)},children:"Inspect URLs"})]})})]},x.path),yt=x.isSitemapsIndex&&Xe?ze.map(st=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Un,{value:st.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ti(st)}),e.jsx("td",{className:"text-secondary",children:st.lastSubmitted?st.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:st.lastDownloaded?st.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Ii(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:$i(st)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!ks||ct,onClick:()=>{_s([st.path])},children:"Resubmit"}),Ft?.sitemapUrl===st.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:he,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ri(st.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:na.isPending,onClick:()=>{oi(st.path)},children:"Inspect URLs"})]})})]},`${x.path}:${st.path}`)):[];return[tt,...yt]})})]}),e.jsx(Es,{page:Gt.page,pageSize:os,visibleRows:Gt.rows.length,totalRows:Gt.totalRows,onPageChange:Gt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:d,onChange:x=>y(x.target.value),onKeyDown:x=>x.key==="Enter"&&void mi()}),e.jsx(P,{type:"button",size:"sm",disabled:je||!Ft?.propertyId||!d.trim(),onClick:Me(mi),children:je?"Inspecting…":"Inspect URL"})]}),k&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:k.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:k.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:hi(k.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:qt(k.crawlTime)})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:M,onClick:()=>{kn(!0)},children:M?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:Le,onChange:x=>Fe(x.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:M,onClick:()=>{kn(!0)},children:"Apply filter"})]}),j.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:j.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-neutral",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:hi(x.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:qt(x.inspectedAt)})]},x.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),g.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:g.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:x.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:qt(x.transitionDate)})]},`${x.url}:${x.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ft&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>Wt(x=>!x),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${Lt?"rotate-90":""}`,"aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted",children:"Setup & Configuration"})]})}),Lt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Je,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:q,disabled:Ze||m.length===0,onChange:x=>A(x.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ze?"Loading properties…":"No properties available"}):m.map(x=>e.jsxs("option",{value:x.siteUrl,children:[x.siteUrl," · ",x.permissionLevel]},x.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ze,onClick:()=>{ni(Ft,!0)},children:Ze?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!q||He,onClick:Me(Mo),children:He?"Saving…":"Save property"})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:S,onChange:x=>V(x.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:K,onChange:x=>w(x.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:sa.isPending||!Ft.propertyId,onClick:Me(Lo),children:sa.isPending?"Queueing…":"Queue sync"}),!Ft.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const lm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function cm({projectName:t,projectId:s}){const n=Cs(),[a,i]=l.useState(null),[r,o]=l.useState(null),[m,c]=l.useState(!1),h=Ie(Ba({client:U,path:{name:t}})),p=h.data?.find(_=>_.connectionType==="gbp"),u=!!p,v=a?{locationName:a}:void 0,j=Ie({...gl({client:U,path:{name:t}}),enabled:u}),b=Ie({...fl({client:U,path:{name:t},query:v}),enabled:u}),g=Ie({...bl({client:U,path:{name:t},query:v}),enabled:u}),f=Ie({...vl({client:U,path:{name:t},query:v}),enabled:u}),k=Ie({...yl({client:U,path:{name:t},query:v}),enabled:u}),O=Ie({...jl({client:U,path:{name:t},query:v}),enabled:u}),q=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>Nl(t),enabled:u});function A(){ft(n,"gbp")}const d=Et({...wl(),onSuccess:_=>{Cr({id:_.runId,projectId:s,kind:Os["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),y=l.useSyncExternalStore(kr,Kn,Kn),S=Object.values(y.runs).some(_=>_.kind===Os["gbp-sync"]&&_.projectId===s),V=d.isPending||S,K=Et({...Sl(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!j.data)return;const _=j.data.locations.filter(ae=>ae.selected);(_.length<=1||!_.some(ae=>ae.locationName===a))&&i(null)},[a,j.data]),l.useEffect(()=>{if(!r||!j.data)return;(a?[a]:j.data.locations.filter(ae=>ae.selected).map(ae=>ae.locationName)).includes(r)||o(null)},[r,j.data,a]),h.isLoading)return null;if(!p){const _=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:_.map((ae,Ne)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:Ne+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ae.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ae.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ae.note})]})]},ae.title))})]})})}const w=b.data,T=j.data?.locations??[],F=T.filter(_=>_.selected),$=g.data?.keywords??[],H=f.data?.lodging??[],ye=k.data?.placeActions??[],ge=O.data?.places??[],z=T.length>0?T[0].accountName:p.domain,ee=a?T.find(_=>_.locationName===a)?.displayName??null:null,ie=a?T.filter(_=>_.locationName===a):F,W=new Set(ie.map(_=>_.locationName)),B=H.filter(_=>W.has(_.locationName)),R=ye.filter(_=>W.has(_.locationName)),se=ge.filter(_=>W.has(_.locationName)),le=new Set(F.map(_=>_.locationName)),de=a?$:$.filter(_=>le.has(_.locationName)),X=!a&&F.length>1,Ae=(q.data??[]).filter(_=>!_.dismissed&&lm.has(_.type)&&(!ee||_.query===ee||_.query===a||_.title.startsWith(ee)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Je,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:V,onClick:()=>d.mutate({client:U,path:{name:t},body:{}}),children:V?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[z?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:z})," · "]}):null,j.data?`${j.data.totalSelected} of ${j.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:_=>i(_.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),F.map(_=>e.jsx("option",{value:_.locationName,children:_.displayName},_.id))]})]}),F.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[Ae.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ae.map(_=>e.jsx("div",{className:["insight-card",Nm(_.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[_.title,_.recommendation?.reason&&e.jsx(Je,{text:_.recommendation.reason})]})},_.id))]}),w&&e.jsx(km,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(dm,{summary:w.profileCompleteness}),ie.length>0&&e.jsx(um,{locations:ie,lodging:B,places:se,placeActions:R,expandedLocation:r,onToggleExpanded:_=>{o(ae=>ae===_?null:_)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),de.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),X&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:de.slice(0,25).map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:_.keyword}),X&&e.jsx("td",{className:"text-muted",children:T.find(ae=>ae.locationName===_.locationName)?.displayName??_.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:_.valueCount!==null?_.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",_.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[_.periodStart,"–",_.periodEnd]})]},`${_.locationName}:${_.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>c(_=>!_),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",T.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:T.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!J()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:T.map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:_.displayName}),e.jsx("td",{className:"text-muted",children:_.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:_.selected?"positive":"neutral",children:_.selected?"Tracked":"Not tracked"})}),!J()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:K.isPending,onClick:()=>K.mutate({client:U,path:{name:t,locationName:_.locationName},body:{selected:!_.selected}}),children:_.selected?"Untrack":"Track"})})]},_.id))})]})})]})]})})}function dm({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:on(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:on(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:on(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:on(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:on(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Je,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${jm(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function um({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const o=new Map(s.map(h=>[h.locationName,h])),m=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const p=c.get(h.locationName)??[];p.push(h),c.set(h.locationName,p)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Je,{text:J()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const p=o.get(h.locationName)??null,u=m.get(h.locationName)??null,v=c.get(h.locationName)??[],j=i===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(oe,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(oe,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:so(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(hm,{location:h})}),e.jsx("td",{children:e.jsx(xm,{lodging:p})}),e.jsx("td",{children:e.jsx(gm,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(bm,{actions:v})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>r(h.locationName),children:j?"Hide":"Details"})})]}),j&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(ym,{location:h,lodging:p,place:u,placeActions:v})})})]},h.id)})})]})})]})}function mm(t){return[{label:"Description",tone:Ms(t.description)?"positive":"neutral",value:Ms(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Ms(t.primaryPhone)?"positive":"neutral",value:Ms(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Ms(t.websiteUri)?"positive":"neutral",value:Ms(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function hm({location:t}){const s=mm(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function xm({lodging:t}){return e.jsx(Ka,{...pm(t)})}function pm(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function gm({place:t,mapsUri:s}){return e.jsx(Ka,{...fm(t,s)})}function fm(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function bm({actions:t}){return e.jsx(Ka,{...vm(t)})}function vm(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function Ka({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function ym({location:t,lodging:s,place:n,placeActions:a}){const i=s?Sm(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(ha,{title:"Owner profile · Business Information",children:[e.jsx(Rt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Rt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Rt,{label:"Description",value:Ms(t.description)?t.description:"Not returned"}),e.jsx(Rt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Rt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Rt,{label:"Open status",value:so(t.openStatus)}),e.jsx(Rt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(ha,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Last checked",value:Mi(s.syncedAt)}),e.jsx(Rt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Rt,{label:"Populated groups",value:i.length>0?i.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(ha,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Places tier",value:n.tier}),e.jsx(Rt,{label:"Last checked",value:Mi(n.syncedAt)}),e.jsx(Rt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Yn(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Yn(r.providerType),r.uri?` · ${wm(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function ha({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Rt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function on(t,s,n){return t===s?"positive":t===0?n:"caution"}function jm(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Nm(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Ms(t){return typeof t=="string"&&t.trim().length>0}function so(t){return t?Yn(t):"Not returned"}function Yn(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function wm(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Mi(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Sm(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Cm(n)).map(([s])=>Yn(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Cm(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function km({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=Cl.filter(b=>(a[b]??0)>0),r=kl.filter(b=>(a[b]??0)>0),o=Object.keys(a).filter(b=>(a[b]??0)>0&&Al(b)==="other").sort((b,g)=>(a[g]??0)-(a[b]??0)),m=Object.keys(a).filter(b=>(a[b]??0)===0).sort(),c=n.map(b=>{const g={date:b.date};for(const[f,k]of Object.entries(b.metrics))g[f]=k;return g}),h=n.find(b=>b.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,u=c.length>0,v=s.dataThroughDate?`Data through ${Ut(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,j=[...i,...o];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),v&&e.jsx("span",{className:"text-[11px] text-muted",children:v})]}),!u||i.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Li,{data:c,metrics:i,kind:"line",firstPending:h,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:j.map(b=>e.jsxs("span",{className:"text-sm text-secondary",children:[zn(b)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[b]??0).toLocaleString()})]},b))})]})]}),u&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Li,{data:c,metrics:r,kind:"area",firstPending:h,lastDate:p})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(b=>zn(b)).join(", ")]})]})}function Li({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Fr,{stroke:qr,vertical:!1}),e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn,minTickGap:24}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(r,o)=>[typeof r=="number"?r.toLocaleString():String(r??0),zn(String(o??""))]}),e.jsx(Gr,{wrapperStyle:{fontSize:11,color:Ht.text},formatter:r=>zn(r)}),a&&i&&e.jsx(nu,{x1:a,x2:i,fill:Ht.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Ht.textDim,fontSize:10}}),s.map((r,o)=>n==="line"?e.jsx(_r,{type:"monotone",dataKey:r,stroke:rt[o%rt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(zs,{type:"monotone",dataKey:r,stackId:"reach",stroke:rt[o%rt.length],fill:rt[o%rt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function Am(t){return Or(us(String(t)))}function Pm(t){return Ss(us(String(t)))}function xa({children:t,label:s="More info",placement:n="top",className:a}){const i=l.useId(),[r,o]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Wd,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Tn=os;function Us(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function pa(t){return t.toLocaleString()}function Rm(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Im(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function $m(t){const s=t.filter(n=>n.kind===Os["backlink-extract"]&&!Ar(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Tm(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function Mm({projectName:t}){const[s,n]=l.useState(null),[a,i]=l.useState(null),[r,o]=l.useState([]),[m,c]=l.useState(null),[h,p]=l.useState(null),[u,v]=l.useState(null),[j,b]=l.useState(Date.now()),[g,f]=l.useState(0),[k,O]=l.useState(!0),[q,A]=l.useState(!1),[d,y]=l.useState(null),S=l.useCallback(async()=>{O(!0),y(null);try{const[z,ee,ie,W,B]=await Promise.all([Pl().catch(()=>null),Rl(t,{excludeCrawlers:!0}).catch(()=>null),Il(t,{limit:Tn,offset:g,excludeCrawlers:!0}).catch(se=>{if(se instanceof Zs&&se.code==="NOT_FOUND")return null;throw se}),$l(t).catch(()=>[]),Tl(t).catch(()=>[])]);c(z),n(ee),i(ie),o(W);const R=$m(B);p(R)}catch(z){y(z instanceof Error?z.message:"Failed to load backlinks")}finally{O(!1)}},[t,g]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!h)return;const z=h.id;let ee=!1;const ie=async()=>{try{const B=await Ta(z);if(ee)return;Ar(B.status)?(p(null),v(B),await S()):p(R=>R?.id===B.id?{...R,...B}:R)}catch{}},W=window.setInterval(()=>{ie()},3e3);return()=>{ee=!0,window.clearInterval(W)}},[h,S]),l.useEffect(()=>{if(!h)return;const z=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(z)},[h]),l.useEffect(()=>{if(!u||u.status==="failed")return;const z=window.setTimeout(()=>v(null),1e4);return()=>window.clearTimeout(z)},[u]);async function V(){A(!0),y(null);try{const z=await Ll(t);p(z)}catch(z){z instanceof Zs&&z.code==="MISSING_DEPENDENCY"?y("DuckDB is not installed. Visit the Backlinks admin page to install it."):y(z instanceof Error?z.message:"Failed to trigger extract")}finally{A(!1)}}const K=l.useMemo(()=>r.slice().sort((z,ee)=>z.queriedAt.localeCompare(ee.queriedAt)).map(z=>({date:z.queriedAt,linkingDomains:z.totalLinkingDomains})),[r]),w=a?.rows??[],T=a?.total??0,F=s?.excludedLinkingDomains??0,$=Math.floor(g/Tn)+1;return l.useEffect(()=>{g>0&&g>=T&&f(0)},[g,T]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),d&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:d})}),h&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Qd,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(oe,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Tm(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",j]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),u&&!h&&e.jsx(pe,{className:`surface-card p-4 mb-4 ${u.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[u.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Lr,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${u.status==="failed"?"text-negative":"text-positive"}`,children:u.status==="failed"?"Extract failed":"Extract complete"}),u.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Ml(u.error)}):u.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return k?e.jsx(pe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):ye()}function ye(){const z=s!==null&&s.totalLinkingDomains>0,ee=u?.status==="failed",ie=s!==null&&s.totalLinkingDomains===0&&!ee,W=m?.status==="ready",B=m?.status==="failed",R=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return z?ge(e.jsxs(e.Fragment,{children:[!J()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Dr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsx(xa,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!J()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Open admin"})})]})):e.jsx(pe,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Hd,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Set up backlinks"})})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"View sync status"})})})]}),B&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})})})]}),W&&!R&&!ie&&!ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:m.release})," is ready. Run an extract for this project."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Hn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Run extract"]}),e.jsx(xa,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!J()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})})})]}),ie&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Hn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsxs(xa,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function ge(z){if(!s)return null;const ee="Linking hosts",ie="linking hosts",W="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:pa(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",ie]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:pa(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ie," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Rm(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ie," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",W," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Im(s.queriedAt),F>0&&e.jsxs(e.Fragment,{children:[" · ",F," excluded domain",F===1?"":"s"]})]}),K.length>=2&&e.jsxs(pe,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:K,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:rt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:rt[0],stopOpacity:0})]})}),e.jsx(vn,{dataKey:"date",tick:ns,stroke:Gs,tickFormatter:Am}),e.jsx(yn,{tick:ns,stroke:Gs,allowDecimals:!1}),e.jsx(jn,{contentStyle:Ws.contentStyle,labelStyle:Ws.labelStyle,itemStyle:Ws.itemStyle,labelFormatter:Pm}),e.jsx(zs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:rt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(pe,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:ee})]})}),e.jsxs("tbody",{children:[w.map(B=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:B.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:pa(B.numHosts)})]},B.linkingDomain)),w.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:F>0&&T===0?`Every referring domain in this ${W} was a crawler/proxy host (${F} hidden).`:`No referring domains in this ${W}.`})})]})]})}),e.jsx(Es,{page:$,pageSize:Tn,visibleRows:w.length,totalRows:T,onPageChange:B=>f((B-1)*Tn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:z})]})}}function Lm({projectName:t}){const s=Ie({...Dl({client:U,path:{name:t}}),staleTime:Pr}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:Va(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:i,providersMentioning:r,providersConfigured:o}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",i," of ",o," engines",e.jsx(Je,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",r," of ",o," engine answers",e.jsx(Je,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(Dm,{data:n}),e.jsx(Em,{data:n}),n.competitorGaps.length>0&&e.jsx(Fm,{data:n})]})}function Dm({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Mn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Mn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Mn,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Mn,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Mn({label:t,value:s,helper:n,tone:a}){const i=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Em({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const i of a.providers)n.add(i.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(qm,{}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(Js,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(Yd,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Om,{provider:i})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function qm(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!1,tone:"cited"}),e.jsx(Qs,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Om({provider:t}){const s=Gm(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Qs,{active:t.cited,tone:"cited"}),e.jsx(Qs,{active:t.mentioned,tone:"mentioned"})]})}function Gm(t){return t.cited&&t.mentioned?"Cited in sources and mentioned in answer":t.cited?"Cited in sources, not mentioned in answer":t.mentioned?"Mentioned in answer, not in sources":"Not cited and not mentioned"}function Qs({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Fm({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Je,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(Js,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Sn="__cited__",Cn="__mentioned__",Qt="__mentionShare__";function no(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:us(n),end:us(a),sweepCount:s.sweepCount??1}}function Xn(t){const s=no(t);if(!s)return"Sweep date unavailable";const n=Ss(s.start),a=Ss(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function _m(t){const s=no(t);return s?Or(s.start):""}function tn(t){return t.trim().toLowerCase()}function Ea(t){return Math.round(t*1e3)/10}function qa(t){return t.byProvider??{}}function Um(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?Sn:Cn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[c]:Ea(u[h])})),series:[c],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(c=>Object.keys(qa(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},p=qa(c);for(const u of o){const v=p[u];h[u]=v?Ea(v[r]):null}return h}),series:o,hasData:a,singleBucket:i}}function ao(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Bm(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Vm(t){return t.servedModelAttribution??{}}function Km(t){return t.modelServiceMismatch??{}}function zm(t){return t.modelPointerChanges??{}}function Qm(t){return t.length>0?t.join(", "):null}function Di(t,s){const n=tn(s);return Object.entries(t).find(([a])=>tn(a)===n)?.[1]}function ls(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function Hm(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Di(qa(a),s))continue;const i=ao(a);return i?Di(i,s)??null:null}return null}function Wm(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const i of a.events){const r=s.get(i.bucketStartDate)??[];r.push({provider:n,event:i}),s.set(i.bucketStartDate,r)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((i,r)=>i.provider.localeCompare(r.provider)||i.event.observedAt.localeCompare(r.event.observedAt))}))}function Ym(t){const s={},n=[];for(const[a,i]of Object.entries(t)){const r=i.events.filter(o=>!o.fromPreWindowAnchor);for(const o of i.events)o.fromPreWindowAnchor&&n.push({provider:a,event:o});r.length>0&&(s[a]={...i,events:r})}return{buckets:Wm(s),beforeWindow:n.sort((a,i)=>a.event.observedAt.localeCompare(i.event.observedAt)||a.provider.localeCompare(i.provider))}}function Xm(t){let s=0,n=0;for(const a of Object.values(t))s+=a.events.length,n+=a.eventTotal??a.events.length;return{shown:s,total:n}}function Jm(t){const s=[];for(const[n,a]of Object.entries(t)){const i=a.eventTotal??a.events.length;i>a.events.length&&s.push({provider:n,shown:a.events.length,total:i})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Zm(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[Qt]:i?.rate==null?null:Ea(i.rate)}}),n=s.map(a=>a[Qt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Qt],hasData:n.length>0,singleBucket:n.length===1}}function eh(t,s,n){return s==="mentionShare"?Zm(t):Um(t,s,n)}function Ei(t,s){for(let n=t.length-1;n>=0;n--){const a=t[n][s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function qi(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Oi(t){return t>0?`+${t}`:`${t}`}function th(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Oi(n.delta)} on ${qi(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Oi(s.delta)} on ${qi(s.date)})`}const sh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],nh=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],ah=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"On non-brand queries, the share of answer-text brand mentions for you and tracked competitors that were you. Pooled only when query classification is unavailable."}],za=rt[2],ih="var(--chart-tooltip-bg)",rh={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ds(t){const s=tn(t);return rh[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Ns(t){return Math.round(t*10)/10}function oh(t){return t===Sn||t===Cn||t===Qt}function io(t){return t===Sn?"Cited":t===Cn?"Mentioned":t===Qt?"Mention share":ds(t)}function dn(t,s){return t===Sn?qs.positive:t===Cn?rt[1]:t===Qt?za:Zd(tn(t),s)}function lh(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function ch(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
2
|
`)}function ea(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function Vn(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${ea(s)}`:"Mention share":"Mentioned"}function Nn(t){return t==="cited"?"citationRate":"mentionRate"}function ro(t,s){return s==="cited"?t.cited:t.mentionedCount}function oo(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function lo(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Oa(t){const s=ao(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[i])=>tn(a).localeCompare(tn(i))).map(([a,i])=>`${ds(a)}: ${ls(i)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function dh(t){return t.some(({event:s})=>s.to.status==="mixed")?qs.caution:t.some(({event:s})=>s.to.status==="unknown")?qs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?rt[4]:qs.positive}function uh(t,s,n){const a=lo(t,s);return a?Xn(a):Ss(us(n))}function mh({partition:t,available:s,counts:n,truncated:a,incompleteHistory:i,served:r,mismatch:o,buckets:m}){const c=l.useId(),h=Object.entries(r).sort(([u],[v])=>u.localeCompare(v)),p=t.buckets.length>0||t.beforeWindow.length>0;return!s||!p?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":c,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:c,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:u,events:v})=>v.map(({provider:j,event:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:uh(m,u,b.observedAt)}),e.jsxs("span",{children:[ds(j),": ",ls(b.from)," → ",ls(b.to)]})]},`${j}-${b.observedAt}-${b.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:u,event:v})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Ss(us(v.observedAt))]}),e.jsxs("span",{children:[ds(u),": ",ls(v.from)," → ",ls(v.to),v.anchorObservedAt?` (last seen ${ls(v.from)} on ${Ss(us(v.anchorObservedAt))})`:""]})]},`before-${u}-${v.observedAt}`))})]}),a.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:[ds(u.provider),": showing the most recent ",u.shown," of ",u.total," changes."]},`truncated-${u.provider}`)),i.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",ds(u)," change."]},`incomplete-${u}`)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([u,v])=>{const j=Qm(v.latestServedModelIds),b=o[u];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Ss(us(v.latestObservation.observedAt))}),e.jsxs("span",{children:[ds(u),": ",j??ls(v.latestObservation.state),b?` — not the ${ls(b.configured)} you selected`:""]})]},`served-${u}`)})})]})]})}function Gi(t){return t===null?"no data":`${t}%`}function ga(t){return t==null?"undefined":`${Ns(t*100)}%`}function hh({active:t,label:s,payload:n,metric:a,mode:i,buckets:r}){if(!t)return null;const o=lo(r,s);if(!o)return null;if(a==="mentionShare"){const c=o.mentionShare.projectMentionSnapshots,h=o.mentionShare.competitorMentionSnapshots,p=c+h,u=o.mentionShare.rate==null?null:Ns(o.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Xn(o)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:za},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",ea(o.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:Gi(u)})]}),p>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",p," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:Oa(o)})]})}const m=i==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?Sn:Cn,value:Ns(o[Nn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Xn(o)}),m.map((c,h)=>{const p=String(c.dataKey??c.name??""),u=i==="byProvider"?oo(o,p,a):null,v=u?.count??ro(o,a),j=u?.total??o.total,b=typeof c.value=="number"?c.value:Ns(u?u.rate*100:o[Nn(a)]*100),g=c.color??dn(p,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:g},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:io(p)}),e.jsx("span",{className:"trend-tooltip-value",children:Gi(b)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[v," / ",j," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${p}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Oa(o)})]})}function xh({buckets:t,metric:s,mode:n,series:a}){const i=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Vn(s,i)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(r=>{let o;if(s==="mentionShare"){const m=r.mentionShare.projectMentionSnapshots,c=r.mentionShare.competitorMentionSnapshots,h=m+c,p=ea(r.mentionShare.scope);o=h>0?`${ga(r.mentionShare.rate)} mention share for ${p}, ${m} of ${h} brand mentions were you`:`mention share undefined for ${p}, no project or competitor brand mentions`}else n==="byProvider"?o=a.map(m=>{const c=oo(r,m,s);return c?`${ds(m)} ${ga(c.rate)} ${Vn(s).toLowerCase()}, ${c.count} of ${c.total} snapshots`:`${ds(m)} no data`}).join("; "):o=`${ga(r[Nn(s)])} ${Vn(s).toLowerCase()}, ${ro(r,s)} of ${r.total} snapshots`;return o+=`; ${Oa(r)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Xn(r)}),e.jsx("td",{children:o})]},r.startDate)})})]})}function fa({options:t,value:s,onChange:n,ariaLabel:a,className:i}){const r=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${i??""}`,children:t.map(o=>{const m=s===o.value,c=o.description?`${r}-${o.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":m,"aria-describedby":c,className:`segmented-option ${m?"segmented-option-active":""}`,onClick:()=>n(o.value),children:o.label}),o.description&&e.jsx("span",{id:c,className:"sr-only",children:o.description})]},o.value)})})}function ph({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,i]=l.useState("all"),[r,o]=l.useState("mentioned"),[m,c]=l.useState("byProvider"),h=l.useMemo(()=>ch(s),[s]),p=Ie({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>El(t,a),staleTime:Pr}),u=p.data??null,v=p.error,j=r==="mentionShare"?"overall":m,b=l.useMemo(()=>u?eh(u,r,j):null,[u,r,j]),g=u?Bm(u):null,f=l.useMemo(()=>Ym(g??{}),[g]),k=l.useMemo(()=>Xm(g??{}),[g]),O=l.useMemo(()=>Jm(g??{}),[g]),q=l.useMemo(()=>Object.entries(g??{}).filter(([,B])=>B.anchorUnavailable).map(([B])=>B).sort(),[g]),A=l.useMemo(()=>u?Vm(u):{},[u]),d=l.useMemo(()=>u?Km(u):{},[u]),y=l.useMemo(()=>u?ql(zm(u)):null,[u]),S=r!=="mentionShare"&&j==="byProvider",V=u?.buckets??[],K=V[V.length-1]?.mentionShare.scope??u?.mentionShareScope??"pooled",w=Vn(r,K),T=r==="cited"?qs.positive:r==="mentionShare"?za:rt[1],F=S?Ht.textDim:T,$=l.useMemo(()=>{const B=new Map(V.map(R=>[R.startDate,_m(R)]));return R=>B.get(String(R))??""},[V]),H=r==="mentionShare"?b?Ei(b.rows,Qt):null:V.length>0?Ns(V[V.length-1][Nn(r)]*100):null,ye=r==="mentionShare"?b?lh(b.rows,Qt):null:V.length>0?Ns(V[0][Nn(r)]*100):null,ge=r==="mentionShare"?b?.rows.filter(B=>typeof B[Qt]=="number").length??0:V.length,z=H!==null&&ye!==null&&ge>1?Ns(H-ye):null,ee=s.length,ie=e.jsxs(e.Fragment,{children:[y?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:y.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Je,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use all query-provider snapshots. Mention share uses non-brand queries when classification is available; pooled means the project has no usable brand identity for a split."})]})]}),H!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:F},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:w}),S&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[H,"%"]}),z!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${z>0?"text-positive-400":z<0?"text-negative-400":"text-muted"}`,children:[z>0?"+":"",z.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(fa,{options:ah,value:r,onChange:o,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),r!=="mentionShare"&&e.jsx(fa,{options:nh,value:m,onChange:c,ariaLabel:"Series"}),e.jsx(fa,{options:sh,value:a,onChange:i,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let W;if(v)W=e.jsx("p",{className:"text-sm text-negative-400",children:Va(v)});else if(p.isLoading&&!u)W=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(r==="mentionShare"&&ee===0)W=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!u||!b)W=null;else{const{rows:B,series:R,hasData:se}=b,le=th(u.queryChanges);if(!se)W=e.jsx("p",{className:"text-sm text-secondary",children:r==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${ea(K)} in this window yet.`:"Run a sweep to start tracking citations and mentions over time."});else if(S&&R.length===0)W=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const de=`${w} rate across ${B.length} ${B.length===1?"sweep":"sweeps"}. Latest ${H}%${z!==null?`, ${z>=0?"up":"down"} ${Math.abs(z).toFixed(1)} points over the period`:""}.`;W=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:de}),e.jsx(xh,{buckets:V,metric:r,mode:j,series:R}),S&&R.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:R.map((X,Ae)=>{const _=Ei(B,X),ae=Hm(V,X),Ne=g===null?"Attribution unavailable":ae?ls(ae):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:dn(X,Ae)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:io(X)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),Ne]})]}),_!==null&&e.jsxs("span",{className:"trend-legend-value",children:[_,"%"]})]},X)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${w} trend chart over ${B.length} ${B.length===1?"bucket":"buckets"}`,children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:B,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Fr,{stroke:qr,vertical:!1}),e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:$,minTickGap:24}),e.jsx(yn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:X=>`${X}%`,tick:ns,tickLine:!1,axisLine:!1,width:40}),e.jsx(jn,{cursor:{stroke:Gs,strokeWidth:1},content:e.jsx(hh,{metric:r,mode:j,buckets:V})}),f.buckets.map(({bucketStartDate:X,events:Ae})=>e.jsx(au,{x:X,stroke:dh(Ae),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${X}`)),R.map((X,Ae)=>e.jsx(_r,{type:"monotone",dataKey:X,name:X,stroke:dn(X,Ae),strokeDasharray:X===Qt?"5 4":void 0,strokeWidth:oh(X)?2.5:2,dot:X===Qt?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:dn(X,Ae),strokeWidth:1.5}:{r:2.5,fill:dn(X,Ae),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:ih},connectNulls:X!==Qt,isAnimationActive:!1},X))]})})}),e.jsx(mh,{partition:f,available:g!==null,counts:k,truncated:O,incompleteHistory:q,served:A,mismatch:d,buckets:V}),le&&e.jsx("p",{className:"visibility-trend-note",children:le})]})}}return e.jsxs("section",{className:"visibility-trend",children:[ie,W]})}const Fi=new Set([hn.queued,hn.running]);function gh({projectName:t}){const s=Cs(),[n,a]=l.useState(""),[i,r]=l.useState(""),[o,m]=l.useState(""),[c,h]=l.useState("__default__"),[p,u]=l.useState(null),v=Ie({...Ol({client:U,path:{name:t}}),staleTime:6e4}),j=Ie({...Gl({client:U}),staleTime:6e4}),b=Ie({...Fl({client:U,path:{name:t},query:{limit:20}}),refetchInterval:w=>w.state.data?.runs.some(T=>Fi.has(T.status))?3e3:!1}),g=b.data?.runs??[];l.useEffect(()=>{!p&&g[0]&&u(g[0].id)},[g,p]);const f=g.find(w=>w.id===p)??null,k=Ie({..._l({client:U,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:f&&Fi.has(f.status)?3e3:!1}),O=k.data??null,q=l.useMemo(()=>vh(n),[n]),A=v.data?.locations??[],d=l.useMemo(()=>{const w=new Map((j.data?.providerCatalog??[]).map(T=>[T.name,T]));return(j.data?.providers??[]).filter(T=>T.configured&&w.get(T.name)?.mode==="api").map(T=>({...T,catalog:w.get(T.name)}))},[j.data]),y=!j.isLoading&&d.length===0,S=d.find(w=>w.name===i)??null;l.useEffect(()=>{i&&!S&&(r(""),m(""))},[i,S]);const V=Et({...Ul(),onSuccess:async w=>{u(w.id),a(""),m(""),await wh(s),Se({title:"Research batch saved",detail:`${w.totalQueries} quer${w.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${w.id}`,dedupeMode:"replace"})},onError:w=>{Se({title:"Could not start research",detail:w instanceof Error?w.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function K(){if(q.length===0||q.length>50||y||V.isPending||J())return;const w=c==="__default__"?void 0:c==="__none__"?null:A.find(T=>T.label===c)??void 0;V.mutate({client:U,path:{name:t},body:{queries:q,...i?{provider:i}:{},...i&&o.trim()?{model:o.trim()}:{},...w!==void 0?{location:w}:{}}})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific queries against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:`one query per line
|
|
3
3
|
e.g. What is the best way to choose an AEO platform?`,value:n,onChange:w=>a(w.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${q.length>50?"text-negative":"text-faint"}`,children:[q.length," ",q.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:i,onChange:w=>{r(w.target.value),m("")},children:[e.jsx("option",{value:"",children:"Project default"}),d.map(w=>e.jsx("option",{value:w.name,children:w.displayName??w.name},w.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:c,onChange:w=>h(w.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),A.map(w=>e.jsx("option",{value:w.label,children:w.label},w.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:S?`Default: ${S.model??S.defaultModel??S.catalog.defaultModel}`:"Choose a provider to select an exact model",value:o,disabled:!S,onChange:w=>m(w.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(S?.catalog.knownModels??[]).map(w=>e.jsx("option",{value:w.id,children:w.displayName},w.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:q.length===0||q.length>50||y||V.isPending,onClick:K,children:[e.jsx(Hn,{size:14}),V.isPending?"Starting research…":`Run ${q.length||""} research ${q.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),y&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Saved research batches"})]}),b.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),g.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more queries to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:g.map(w=>e.jsxs("tr",{className:p===w.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>u(w.id),children:yh(w.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:w.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:w.requestedModel??w.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:w.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[w.completedQueries+w.failedQueries,"/",w.totalQueries]}),e.jsx("td",{children:e.jsx(oe,{tone:co(w.status),children:w.status})})]},w.id))})]})})]})]}),e.jsx(fh,{detail:O,isLoading:k.isFetching})]})}function fh({detail:t,isLoading:s}){const[n,a]=l.useState(null);l.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const i=t?.queries.find(r=>r.id===n)??t?.queries[0]??null;return e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${jh(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(oe,{tone:co(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(r=>e.jsxs("tr",{className:i?.id===r.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(r.id),children:r.query})}),e.jsx("td",{children:e.jsx(oe,{tone:Nh(r.status),children:r.status})}),e.jsx("td",{children:e.jsx(oe,{tone:r.answerMentioned===!0?"positive":r.answerMentioned===!1?"neutral":r.status===Ds.failed?"negative":"caution",children:r.answerMentioned===null?r.status===Ds.failed?"Unavailable":"Pending":r.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(oe,{tone:r.citationState==="cited"?"positive":r.citationState==="not-cited"?"neutral":r.status===Ds.failed?"negative":"caution",children:r.citationState===null?r.status===Ds.failed?"Unavailable":"Pending":r.citationState==="cited"?"Cited":"Not cited"})})]},r.id))})]})}),e.jsx(bh,{query:i,isLoading:s})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function bh({query:t,isLoading:s}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Ds.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n},n))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n.replace(/^www\./,"")},n))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.groundingSources.map((n,a)=>{const i=Ts(n.uri),r=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:r}):e.jsx("span",{className:"truncate text-secondary",children:r}),i&&e.jsx(Xd,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${n.uri}-${a}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function vh(t){const s=new Set;return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>{const a=n.toLocaleLowerCase();return!n||s.has(a)?!1:(s.add(a),!0)})}function yh(t){const s=new Date(t);return Number.isNaN(s.valueOf())?t:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(s)}function jh(t){return t.length>8?t.slice(0,8):t}function co(t){return t===hn.completed?"positive":t===hn.partial?"caution":t===hn.failed?"negative":"neutral"}function Nh(t){return t===Ds.completed?"positive":t===Ds.failed?"negative":"neutral"}async function wh(t){await ft(t,"researchRuns")}const Ga=new Set(["queued","seeding","probing"]);function Sh({projectName:t}){const[s,n]=l.useState("find");return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query discovery"}),e.jsx("h2",{children:"Discover or research queries"})]})}),e.jsxs("div",{className:"inline-flex rounded-md border border-default bg-surface p-1",role:"tablist","aria-label":"Query discovery workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s==="find",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="find"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("find"),children:"Find queries"}),e.jsx("button",{type:"button",role:"tab","aria-selected":s==="research",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="research"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("research"),children:"Research queries"})]}),e.jsx("div",{className:"mt-4",children:s==="find"?e.jsx(Ch,{projectName:t}):e.jsx(gh,{projectName:t})})]})}function Ch({projectName:t}){const s=Cs(),[n,a]=l.useState(null),[i,r]=l.useState(""),[o,m]=l.useState("100"),c=Ie({...Bl({client:U,path:{name:t},query:{limit:"10"}}),refetchInterval:d=>d.state.data?.some(S=>Ga.has(S.status))?3e3:!1}),h=c.data??[];l.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const p=h.find(d=>d.id===n)??null,u=Ie({...Vl({client:U,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&Ga.has(p.status)?3e3:!1}),v=u.data??null,j=Ie({...Kl({client:U,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),b=Et({mutationFn:()=>{const d={},y=i.trim();y&&(d.icpDescription=y);const S=Number.parseInt(o,10);return Number.isFinite(S)&&S>0&&(d.maxProbes=S),zl(t,d)},onSuccess:async d=>{a(d.sessionId),r(""),await Ui(s,t,d.sessionId),Se({title:"Discovery started",detail:`Run ${ba(d.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${d.sessionId}`,dedupeMode:"replace"})},onError:d=>{Se({title:"Discovery failed to start",detail:d instanceof Error?d.message:"Could not start discovery.",tone:"negative"})}}),g=Et({mutationFn:d=>{if(!n)throw new Error("Select a completed discovery session first.");return Ql(t,n,d)},onSuccess:async d=>{await Ui(s,t,d.sessionId),s.invalidateQueries({queryKey:Rr({client:U})}),s.invalidateQueries({predicate:y=>Array.isArray(y.queryKey)&&y.queryKey[0]==="projects"&&y.queryKey.length>1}),Se({title:"Queries added",detail:Rh(d),tone:"positive",dedupeKey:`discovery:promote:${d.sessionId}`,dedupeMode:"replace"})},onError:d=>{Se({title:"Could not add queries",detail:d instanceof Error?d.message:"Could not add queries from this run.",tone:"negative"})}}),f=v??p,k=j.data??null,O=(k?.queriesByBucket.cited.length??0)+(k?.queriesByBucket.aspirational.length??0),q=l.useMemo(()=>(v?.probes??[]).slice(0,30),[v?.probes]);async function A(){try{const d=await c.refetch();if(d.error)throw d.error;const y=d.data?.length??0;Se({title:"Discovery sessions refreshed",detail:`${y} recent session${y===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(d){Se({title:"Discovery refresh failed",detail:d instanceof Error?d.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:J()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:c.isFetching,onClick:()=>{A()},children:[e.jsx(Qn,{className:`size-3.5 ${c.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(oe,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:i,onChange:d=>r(d.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:o,onChange:d=>m(d.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:b.isPending,onClick:()=>b.mutate(),children:[e.jsx(Hn,{size:14}),b.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),c.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),h.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:h.map(d=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===d.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(d.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:ba(d.id)}),e.jsx(oe,{tone:_i(d.status),children:d.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",d.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",d.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",d.wastedCount??0]})]})]},d.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:f?ba(f.id):"No run selected"})]}),f&&e.jsx(oe,{tone:_i(f.status),children:f.status})]}),f?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(vs,{label:"Questions tested",value:f.probeCount??0}),e.jsx(vs,{label:"Cited queries",value:f.citedCount??0,tone:"positive"}),e.jsx(vs,{label:"Worth tracking",value:f.aspirationalCount??0,tone:"caution"}),e.jsx(vs,{label:"Skip",value:f.wastedCount??0,tone:"negative"})]}),f.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:f.error}),f.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:f.warning}),f.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:f.icpDescription})]}),f.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:f.competitorMap.slice(0,8).map(d=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[d.domain," ",e.jsx("span",{className:"text-muted",children:d.hits})]},d.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),f?.status==="completed"&&e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Choose queries to track"})]}),!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:g.isPending||O===0,onClick:()=>g.mutate(void 0),children:[e.jsx(Lr,{size:14}),g.isPending?"Adding…":"Add recommended queries"]})]}),j.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):k?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(vs,{label:"Queries to add",value:O,tone:"positive"}),e.jsx(vs,{label:"Cited queries",value:k.queriesByBucket.cited.length,tone:"positive"}),e.jsx(vs,{label:"Worth tracking",value:k.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(vs,{label:"Skip",value:k.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Adds Cited queries and Worth tracking queries, plus recurring competitor sites. Skip items remain available for review only."}),k.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.suggestedCompetitors.map(d=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[d.domain," ",e.jsx("span",{className:"text-muted",children:d.hits})]},d.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),u.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),q.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"})]})}),e.jsx("tbody",{children:q.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:d.query}),e.jsx("td",{children:e.jsx(oe,{tone:kh(d.bucket),children:Ph(d.bucket)})}),e.jsx("td",{className:"text-secondary",children:d.citedDomains.length>0?d.citedDomains.slice(0,3).join(", "):"-"})]},d.id))})]})})]})]})]})]})}function vs({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function _i(t){return t==="completed"?"positive":t==="failed"?"negative":Ga.has(t)?"caution":"neutral"}function kh(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Ah={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Ph(t){return t?Ah[t]:"Not classified"}function ba(t){return t.length>8?t.slice(0,8):t}function Rh(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,a=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${a>0?`; ${a} already tracked`:""}.`}async function Ui(t,s,n){await Promise.all([ft(t,"discovery"),t.invalidateQueries({queryKey:Hl({client:U})})])}function Bi(t){return`${(t*100).toFixed(1)}%`}function Ih({projectName:t}){const[s,n]=l.useState("changes"),[a,i]=l.useState(null),[r,o]=l.useState(null),m=Ie({...Wl({client:U,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=Ie({...Yl({client:U,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(c.data??[]).filter(f=>(f.status==="completed"||f.status==="partial")&&f.trigger!=="probe").reverse(),p=r??h[0]?.id??"",u=a??h.find(f=>f.id!==p)?.id??"",v=!!(u&&p&&u!==p),j=Ie({...Xl({client:U,path:{name:t},query:{run1:u,run2:p}}),enabled:s==="compare"&&v}),b=m.data??[],g=j.data?.diff.filter(f=>f.changed||f.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([f,k])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===f,className:`filter-chip ${s===f?"filter-chip-active":""}`,onClick:()=>n(f),children:k},f))}),s==="changes"?e.jsx(iu,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),m.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!m.isLoading&&b.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,b.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:b.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(f.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.mentionedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Bi(f.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.citedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Bi(f.overallCitedRate)})]},f.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:u,onChange:f=>i(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:p,onChange:f=>o(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]})]}),c.isLoading||j.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&h.length<2?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:"Run another answer visibility sweep before comparing historical evidence."})]}):null,j.data&&g.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,g.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:g.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:f.query??"Archived query"}),e.jsx("td",{children:e.jsxs(oe,{tone:f.changed?"caution":"neutral",children:[f.run1State??"none"," → ",f.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(oe,{tone:f.visibilityChanged?"caution":"neutral",children:[f.run1MentionState??"none"," → ",f.run2MentionState??"none"]})})]},f.queryId??f.query??"unknown"))})]})}):null]}):null]})}const Vi={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},$h={contract:null,assessment:null,googleAds:Vi,gtm:Vi,snapshots:[]};function Th(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Eh(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Mh(t){switch(t){case"configured":return{label:"Configured",detail:"The conversion is declared, but the static configuration is not yet proven consistent.",tone:"caution"};case"static-mismatch":return{label:"Static mismatch",detail:"Stored configuration does not match the declared conversion. Review the failing checks before relying on it.",tone:"negative"};case"statically-consistent":return{label:"Statically consistent",detail:"Stored Google Ads and Tag Manager configuration aligns with the declared conversion.",tone:"positive"};case"runtime-unverified":return{label:"Runtime verification needed",detail:"The stored configuration aligns, but a real browser event has not been observed.",tone:"caution"};case"observed":return{label:"Observed",detail:"Stored static evidence and a runtime observation support this conversion path.",tone:"positive"};case"not-configured":return{label:"Setup needed",detail:"Connect both providers, select their resources, then declare the conversion Canonry should inspect.",tone:"neutral"};case"contract-selection-required":return{label:"Choose conversion",detail:"Choose one of the declared conversions before Canonry evaluates its evidence.",tone:"neutral"};case"assessment-loading":return{label:"Checking configuration",detail:"Canonry is loading the selected conversion assessment.",tone:"neutral"};case"assessment-unavailable":return{label:"Assessment unavailable",detail:"The selected conversion could not be assessed. Retry before treating static evidence as current.",tone:"negative"}}}function Lh(t){switch(t.googleAds.state){case"not-connected":return{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."};case"selection-required":return{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."};case"stale":return{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."};default:return null}}function Dh(t){switch(t.gtm.state){case"not-connected":return{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."};case"selection-required":return{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."};case"stale":return{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."};default:return null}}function uo(t){return t.googleAds.state==="not-connected"?{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."}:t.googleAds.state==="unavailable"||t.gtm.state==="unavailable"?{id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."}:t.googleAds.state==="selection-required"?{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."}:t.googleAds.state==="stale"?{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."}:t.gtm.state==="not-connected"?{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."}:t.gtm.state==="selection-required"?{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."}:t.gtm.state==="stale"?{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."}:t.contractSelectionRequired?{id:"select-contract",label:"Select conversion",detail:"Choose the declared conversion Canonry should assess."}:t.contract?t.assessmentState==="loading"?{id:"waiting-for-integrity",label:"Checking configuration…",detail:"Canonry is loading the selected conversion assessment."}:t.assessmentState==="unavailable"?{id:"retry-integrity",label:"Retry assessment",detail:"Retry the selected conversion assessment before acting on its evidence."}:t.assessment?.status==="runtime-unverified"?{id:"review-runtime-verification",label:"Review runtime verification",detail:"Static configuration is aligned. Verify a real browser event separately."}:t.assessment?.status==="configured"&&qh(t)?{id:"review-findings",label:"Review findings",detail:"Resolve the mismatched or unknown checks before treating this conversion as ready."}:{id:"sync-static-evidence",label:"Refresh static evidence",detail:"Queue fresh read-only Google Ads and Tag Manager observations."}:{id:"declare-contract",label:"Declare conversion",detail:"Name the website event, Google Ads action, and Tag Manager tag that must agree."}}function Eh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function qh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function mo(t){switch(t){case"connected":return{label:"Connected",tone:"positive"};case"stale":return{label:"Needs refresh",tone:"caution"};case"selection-required":return{label:"Selection needed",tone:"caution"};case"not-connected":return{label:"Not connected",tone:"neutral"};case"unavailable":return{label:"Unavailable",tone:"negative"}}}function Oh(t,s){return t==="configured"?s==="not-configured"||s==="contract-selection-required"?"neutral":"positive":t==="static"?s==="assessment-unavailable"?"negative":s==="assessment-loading"?"neutral":s==="static-mismatch"?"negative":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"positive":s==="configured"?"caution":"neutral":s==="observed"?"positive":s==="runtime-unverified"?"caution":"neutral"}function Gh(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function Ps(t){return t.length<=12?t:`…${t.slice(-10)}`}function Fh(t){const s=[];return t.googleAds.requirePrimaryAction&&s.push("primary action"),t.googleAds.requireBiddableGoal&&s.push("biddable goal"),s.length>0?s.join(" and "):"No bidding-goal assertion"}function _h(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"No additional event fields required"}const va={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function Ki(t){return t.outcome==="pass"?{label:va[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:va[t.code],tone:"negative",outcome:"Fail"}:{label:va[t.code],tone:"caution",outcome:"Unknown"}}function Uh(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Bh(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("conversion value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"no additional event fields"}function Vh(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function zi({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:i}){const r=mo(s.state),o=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(oe,{tone:r.tone,children:r.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),o?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:o}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${qt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const Kh="A conversion names the website event, the Google Ads conversion action, and the Tag Manager tag that must agree. It needs both connections selected because it references resources from each.",zh="Available once Google Ads and Tag Manager are connected.",Qh="Check that a conversion is wired the same way in Google Ads and Tag Manager, so the numbers you optimise against are the ones your site actually sends. Canonry only reads the configuration; it never changes or publishes it.";function Hh({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:i,actionError:r}){const o=t.googleAds.state==="connected",m=t.gtm.state==="connected",c=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",p=c||h||t.gtm.state==="unavailable",u={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},v=!o&&!m,j=[{title:"Google Ads",state:t.googleAds.state,ready:o,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:c?u:Lh(t)},{title:"Tag Manager",state:t.gtm.state,ready:m,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?u:Dh(t)}],b=o&&m&&!p?uo(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Je,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),v?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Qh}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Je,{text:Kh})]}),b&&s?e.jsx(Ye,{type:"button",disabled:i,onClick:()=>s(b.id),children:i?"Working…":b.label}):e.jsx("p",{className:"text-sm text-secondary",children:zh})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:j.map(g=>{const f=g.ready?{label:"Ready",tone:"positive"}:mo(g.state),k=g.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:g.title}),e.jsx(oe,{tone:f.tone,children:f.label}),g.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:g.summary}):null,k&&s?k.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:()=>s(k.id),children:i?"Working…":k.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:()=>s(k.id),children:i?"Working…":k.label}):null,g.summary&&g.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":g.changeLabel,disabled:i,onClick:g.onChange,children:"Change"}):null]},g.title)})}),r?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:r}):null]})]})}function Wh({workspace:t=$h,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:i=[],selectedContractId:r=null,onSelectContract:o,contractError:m=null,onRetryContracts:c,onRetryEvidence:h,onChangeGoogleAdsSelection:p,onChangeGtmSelection:u,onAddContract:v}){const j=Th(t),b=Mh(j),g=uo(t),f=t.assessment?.findings??[],k=f.filter(d=>d.outcome!=="pass"),O=f.filter(d=>d.outcome==="pass"),q=k.some(d=>d.outcome==="fail")?"negative":"caution";return i.length===0&&t.contract===null&&!t.contractSelectionRequired&&m===null?e.jsx(Hh,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:p,onChangeGtmSelection:u,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(oe,{tone:b.tone,children:b.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",qt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:b.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(d=>e.jsxs("li",{className:"break-words",children:[Vh(d)," ",d.kind,", captured ",qt(d.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",d.id,")"]})]},d.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?g.id==="review-findings"||g.id==="review-runtime-verification"||g.id==="retry-connection-status"||g.id==="select-contract"||g.id==="retry-integrity"||g.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||g.id==="waiting-for-integrity",onClick:()=>s(g.id),children:n?"Working…":g.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(g.id),children:n?"Working…":g.label}):g.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):j==="runtime-unverified"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:g.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),i.length>0&&v?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:v,children:"Add conversion"}):null]}),i.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:r??"",onChange:d=>o?.(d.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),i.map(d=>e.jsx("option",{value:d.id,children:d.name},d.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:Fh(t.contract)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Tag Manager"}),e.jsxs("dd",{className:"mt-1 text-sm text-secondary",children:[t.contract.gtm.triggerIds.length," ",t.contract.gtm.triggerIds.length===1?"trigger":"triggers"," and ",t.contract.gtm.variableIds.length," ",t.contract.gtm.variableIds.length===1?"variable":"variables"," required"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Runtime event fields"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:_h(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:Ps(t.contract.googleAds.customerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads conversion action"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:Ps(t.contract.googleAds.conversionActionId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager container"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:Ps(t.contract.gtm.containerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager tag"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:Ps(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),m?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:m}),c?e.jsx(P,{type:"button",variant:"outline",onClick:c,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),k.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(oe,{tone:q,children:[k.length," ",k.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:k.map(d=>{const y=Ki(d);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:y.label}),e.jsx(oe,{tone:y.tone,children:y.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",d.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",d.code]}),d.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",d.evidenceIds.join(", ")]}):null]},`${d.code}:${d.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Je,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(d=>{const y=Oh(d.key,j);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${y==="positive"?"bg-positive-fill":y==="caution"?"bg-caution-fill":y==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:d.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:d.detail}),e.jsx(oe,{tone:y,children:Gh(d.key,j)})]},d.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[zi({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:p}:{},actionPending:n}),zi({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:u}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&h?e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:d.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:d.kind}),e.jsx("td",{className:"text-secondary",children:qt(d.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:Ps(d.id)})]},d.id))})]})})]}):null,O.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[O.length," ",O.length===1?"passing check":"passing checks"," from the latest assessment"]}),e.jsx("div",{className:"findings-table-wrap mt-3",children:e.jsxs("table",{className:"findings-table",children:[e.jsx("caption",{className:"sr-only",children:"Conversion integrity findings"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Check"}),e.jsx("th",{scope:"col",children:"Result"}),e.jsx("th",{scope:"col",children:"Subject"})]})}),e.jsx("tbody",{children:O.map(d=>{const y=Ki(d);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:y.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",d.code]}),d.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",d.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(oe,{tone:y.tone,children:y.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:d.subject})]},`${d.code}:${d.subject}`)})})]})})]}):null,j==="runtime-unverified"?e.jsxs("section",{id:"conversion-integrity-runtime-guidance",className:"page-section-divider","aria-labelledby":"conversion-integrity-runtime-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Runtime verification"}),e.jsx("h3",{id:"conversion-integrity-runtime-title",className:"text-base font-semibold text-heading",children:"Runtime verification checklist"})]})}),e.jsxs("ol",{className:"max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted",children:[e.jsxs("li",{children:["Use a controlled browser session on ",Uh(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:Ps(t.contract.gtm.tagId)})," fires with ",Bh(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:Ps(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Rs=3e4,Qi={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Ct="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",zt="text-sm font-medium text-secondary";function Hi(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:ut(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Ln(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Yh(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Google Ads connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Google Ads OAuth connection is stored for this project.",lastSnapshotAt:null};if(t.status==="selection-required"){const i=t.connection.selection.customerId;return i?{state:"stale",selection:`Selected customer ${i}`,...s,evidence:"A customer is selected, but Canonry needs a fresh conversion-goal observation.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}:{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs a customer account selection.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}const a=t.selectedCustomer;return{state:t.status,selection:a.descriptiveName??`Selected customer ${a.customerId}`,...s,evidence:t.status==="stale"?"The selected customer needs a fresh conversion-goal observation.":"Selected customer and conversion-goal evidence are stored.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}function Xh(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Jh(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Tag Manager connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Tag Manager OAuth connection is stored for this project.",lastSnapshotAt:null};const a=t.selection;return t.status==="selection-required"||!a.accountId||!a.containerId?{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs an account and container selection.",lastSnapshotAt:t.connection.lastSnapshotAt}:{state:t.status,selection:Xh(a.containerId,a.accountId,a.workspaceId),...s,evidence:t.status==="stale"?"The selected container needs a fresh static configuration observation.":"Selected container configuration evidence is stored.",lastSnapshotAt:t.connection.lastSnapshotAt}}function Zh(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:Ln(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Ln(t.triggerIds),variableIds:Ln(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Ln(t.productionHosts)}}}function Wi(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function Dn(t,s,n){if(!s)return null;const a=s.totalAccessible===1?t:`${t}s`;return s.truncated?`Incomplete result: showing ${n} of ${s.totalAccessible} accessible ${a}. Use the CLI or API if the resource is not shown.`:`${s.totalAccessible} accessible ${a} found.`}function En(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function qn({id:t,label:s,value:n,onChange:a,children:i,disabled:r=!1}){return e.jsxs("label",{htmlFor:t,className:zt,children:[s,e.jsx("select",{id:t,className:Ct,value:n,onChange:o=>a(o.target.value),disabled:r,children:i})]})}function Bs({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:i=>n(i.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function Yi({providerLabel:t,disabled:s,onDisconnect:n}){const[a,i]=l.useState(!1),[r,o]=l.useState(!1),[m,c]=l.useState(null),h=l.useRef(null),p=l.useRef(null),u=l.useRef(!1);l.useEffect(()=>{const g=u.current;u.current=a,a?p.current?.focus():g&&h.current?.querySelector("button")?.focus()},[a]);function v(){c(null),i(!0)}function j(){c(null),i(!1)}async function b(){o(!0),c(null);try{await n()}catch(g){c(ut(g)),o(!1)}}return e.jsx("div",{ref:h,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(P,{ref:p,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:r,onClick:j,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||r,onClick:()=>{b()},children:r?"Disconnecting…":`Disconnect ${t}`})]}),m?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:m}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:v,children:["Disconnect ",t]})})}function Xi({id:t,label:s,options:n,synced:a,loading:i,failed:r,onRetry:o,emptyHint:m,value:c,onChange:h}){const p=n.some(g=>g.id===c),[u,v]=l.useState(!1),j=u||c!==""&&!p&&n.length>0,b=e.jsx("label",{htmlFor:t,className:zt,children:s});return i?e.jsxs("div",{children:[b,e.jsx("select",{id:t,className:Ct,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):r?e.jsxs("div",{children:[b,e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:o,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[b,e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":m})]}):e.jsxs("div",{children:[b,j?e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}):e.jsxs("select",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(g=>e.jsxs("option",{value:g.id,children:[g.name,g.detail?` (${g.detail})`:"",g.active?"":" — inactive"]},g.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{v(!j),h("")},children:j?"Choose from synced list":"Enter an ID manually"})]})}function ex({projectId:t,projectName:s}){const n=Ir(),[a,i]=l.useState(null),[r,o]=l.useState(null),[m,c]=l.useState(!1),[h,p]=l.useState(""),[u,v]=l.useState(null),[j,b]=l.useState(!1),[g,f]=l.useState(!1),[k,O]=l.useState(""),[q,A]=l.useState(""),[d,y]=l.useState(""),[S,V]=l.useState(""),[K,w]=l.useState(""),[T,F]=l.useState(!1),[$,H]=l.useState(Qi),[ye,ge]=l.useState(null),z=l.useRef(null),ee=Ie({...Jl({client:U,path:{name:s}}),staleTime:Rs}),ie=Ie({...Zl({client:U,path:{name:s}}),staleTime:Rs}),W=Ie({...ec({client:U,path:{name:s}}),staleTime:Rs}),B=Ie({...tc({client:U,path:{name:s}}),staleTime:Rs}),R=B.data,se=Ie({...sc({client:U,path:{name:s},query:{limit:5}}),staleTime:Rs}),le=Ie({...nc({client:U,path:{name:s},query:{limit:5}}),staleTime:Rs}),de=W.data??[],Ae=(ye?de.find(N=>N.id===ye)??null:null)??(de.length===1?de[0]??null:null),_=de.length>1&&!Ae,ae=Ie({...ac({client:U,path:{name:s,contractId:Ae?.id??""}}),enabled:!!Ae,staleTime:Rs}),Ne=Ie({...ic({client:U,path:{name:s}}),enabled:u==="google-ads"&&ee.data?.connected===!0,staleTime:0}),Le=Ie({...rc({client:U,path:{name:s}}),enabled:u==="gtm"&&ie.data?.connected===!0,staleTime:0}),Fe=Ie({...oc({client:U,path:{name:s,accountId:d}}),enabled:u==="gtm"&&!!d,staleTime:0}),Pe=Ie({...lc({client:U,path:{name:s,accountId:d,containerId:S}}),enabled:u==="gtm"&&!!d&&!!S,staleTime:0}),Qe=Et(cc({client:U})),ue=Et(dc({client:U})),we=Et(uc({client:U})),Ze=Et(mc({client:U})),_e=Et(hc({client:U})),He=Et(xc({client:U})),$e=Et(pc({client:U})),Ce=Et(gc({client:U})),E=Et(fc({client:U}));l.useEffect(()=>{if(u!=="google-ads"||j||!ee.isSuccess)return;const N=ee.data.connection?.selection;O(N?.customerId??""),A(N?.loginCustomerId??""),b(!0)},[j,ee.data,ee.isSuccess,u]),l.useEffect(()=>{if(u!=="gtm"||g||!ie.isSuccess)return;const N=ie.data.selection;y(N?.accountId??""),V(N?.containerId??""),w(N?.workspaceId??""),f(!0)},[g,ie.data,ie.isSuccess,u]),l.useEffect(()=>{!ye||!W.data||W.data.some(N=>N.id===ye)||ge(null)},[W.data,ye]);const M=l.useMemo(()=>{const N=se.data?.snapshots??[],re=le.data?.snapshots??[],at=[...N.map(Vt=>({id:Vt.id,provider:"google-ads",kind:Vt.kind,capturedAt:Vt.capturedAt})),...re.map(Vt=>({id:Vt.id,provider:"gtm",kind:Vt.kind,capturedAt:Vt.capturedAt}))].sort((Vt,Xt)=>Xt.capturedAt.localeCompare(Vt.capturedAt)).slice(0,5),Re=[],gt=ae.data?.googleAdsSnapshot,rs=ae.data?.gtmSnapshot;return gt&&Re.push({id:gt.id,provider:"google-ads",kind:gt.kind,capturedAt:gt.capturedAt}),rs&&Re.push({id:rs.id,provider:"gtm",kind:rs.kind,capturedAt:rs.capturedAt}),{contract:ae.data?.assessment.contract??Ae,assessment:ae.data?.assessment??null,contractSelectionRequired:_,assessmentState:Ae?ae.isError?"unavailable":ae.isLoading?"loading":void 0:void 0,assessmentError:ae.isError?ut(ae.error):null,googleAds:Yh(ee.data,Hi(se.data?.total??0,se.isLoading,se.isError,se.error),ee.isError),gtm:Jh(ie.data,Hi(le.data?.total??0,le.isLoading,le.isError,le.error),ie.isError),snapshots:at,assessmentEvidenceSnapshots:Re}},[Ae,_,se.data,se.error,se.isError,se.isLoading,ee.data,ee.isError,le.data,le.error,le.isError,le.isLoading,ie.data,ie.isError,ae.data,ae.error,ae.isError,ae.isLoading]),L=l.useSyncExternalStore(kr,Kn,Kn),je=Object.values(L.runs).some(N=>N.projectId===t&&(N.kind===Os["google-ads-sync"]||N.kind===Os["gtm-sync"])),qe=Qe.isPending||ue.isPending||we.isPending||Ze.isPending||_e.isPending||He.isPending||$e.isPending||Ce.isPending||E.isPending||je;async function Y(){await Promise.all([ee.refetch(),ie.refetch(),W.refetch(),se.refetch(),le.refetch(),B.refetch(),Ae?ae.refetch():Promise.resolve()])}async function Be(N){await Y();for(let re=0;re<10&&!N();re+=1)await new Promise(at=>setTimeout(at,1500)),await Y()}function mt(){const N=document.activeElement;z.current=N instanceof HTMLElement?N:null}function ot(N){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(N);return}globalThis.setTimeout(N,0)}function De(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Oe(N){if(!N)return;!N.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!N.hasAttribute("tabindex")&&(N.tabIndex=-1),N.focus({preventScroll:!0})}function xt(N,re=N){const at=document.getElementById(N);at instanceof HTMLDetailsElement&&(at.open=!0);const Re=at?.scrollIntoView;typeof Re=="function"&&Re.call(at,{behavior:De()?"auto":"smooth",block:"start"}),Oe(document.getElementById(re)??at)}function We(N,re){mt(),ot(()=>xt(N,re))}function Ve(){const N=z.current;z.current=null,N&&ot(()=>{N.isConnected&&N.focus({preventScroll:!0})})}function Te(){i(null),c(!1),Ve()}function jt(){i(null),v(null),Ve()}function Tt(){i(null),F(!1),Ve()}function Ue(){i(null),v(null),c(!0),We("google-ads-connect-panel","google-ads-connect-title")}function Ge(){i(null),O(""),A(""),b(!1),v("google-ads"),c(!1),We("google-ads-selection-panel","google-ads-selection-title")}function bt(){i(null),y(""),V(""),w(""),f(!1),v("gtm"),c(!1),We("gtm-selection-panel","gtm-selection-title")}function Ke(){i(null),F(!0),We("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Nt(N,re){Cr({id:N.id,projectId:N.projectId,kind:N.kind,projectLabel:s,sourceAction:re}),Se({title:re==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${N.id}`,dedupeMode:"replace"})}async function kt(){ts(n),i(null);try{const N=await Qe.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});p(""),c(!1),o("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Wi(N.authorizationUrl,()=>{Y(),o(null),Ve()})}catch(N){i(ut(N))}}async function vt(){ts(n),i(null);try{const N=await ue.mutateAsync({path:{name:s},body:{provider:"gtm"}});o("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),Wi(N.authorizationUrl,()=>{Y(),o(null),Ve()})}catch(N){i(ut(N))}}async function At(){if(ts(n),!k){i("Select a Google Ads customer before saving.");return}i(null);try{await we.mutateAsync({path:{name:s},body:{customerId:k,...q.trim()?{loginCustomerId:q.trim()}:{}}}),v(null),Ve(),await Be(()=>ee.data?.selectedCustomer!=null)}catch(N){i(ut(N))}}async function lt(){if(ts(n),!d||!S){i("Select a Tag Manager account and container before saving.");return}i(null);try{await Ze.mutateAsync({path:{name:s},body:{accountId:d,containerId:S,...K?{workspaceId:K}:{}}}),v(null),Ve(),await Be(()=>ie.data?.status==="connected")}catch(N){i(ut(N))}}async function G(){ts(n),i(null),await $e.mutateAsync({path:{name:s}}),v(null),c(!1),O(""),A(""),b(!1),o(null),await Y(),Se({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,ot(()=>Oe(document.getElementById("conversion-integrity-title")))}async function ke(){ts(n),i(null),await Ce.mutateAsync({path:{name:s}}),v(null),y(""),V(""),w(""),f(!1),o(null),await Y(),Se({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,ot(()=>Oe(document.getElementById("conversion-integrity-title")))}async function fe(){ts(n),i(null);try{const N=await _e.mutateAsync({path:{name:s}});Nt(N,"google-ads-sync")}catch(N){i(ut(N))}}async function he(){ts(n),i(null);try{const N=await He.mutateAsync({path:{name:s}});Nt(N,"gtm-sync")}catch(N){i(ut(N))}}async function Mt(){ts(n),i(null);try{const N=await Promise.allSettled([_e.mutateAsync({path:{name:s}}),He.mutateAsync({path:{name:s}})]),[re,at]=N;re.status==="fulfilled"&&Nt(re.value,"google-ads-sync"),at.status==="fulfilled"&&Nt(at.value,"gtm-sync");const Re=N.find(gt=>gt.status==="rejected");if(Re?.status==="rejected")throw Re.reason}catch(N){i(ut(N))}}async function ct(){ts(n);const N=ee.data?.connection?.selection.customerId,re=ie.data?.selection;if(!N||!re?.accountId||!re.containerId){i("Select Google Ads and Tag Manager resources before declaring a conversion.");return}i(null);try{const at=await E.mutateAsync({path:{name:s},body:Zh($,N,{accountId:re.accountId,containerId:re.containerId})});H(Qi),F(!1),Ve(),(await W.refetch()).data?.some(gt=>gt.id===at.id)&&ge(at.id)}catch(at){i(ut(at))}}function Pt(N){switch(N){case"connect-google-ads":Ue();return;case"connect-gtm":mt(),vt();return;case"select-google-ads":Ge();return;case"select-gtm":bt();return;case"sync-google-ads":fe();return;case"sync-gtm":he();return;case"sync-static-evidence":Mt();return;case"declare-contract":Ke();return;case"review-findings":We("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":We("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Y();return;case"select-contract":We("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ae.refetch();return;case"waiting-for-integrity":return}}const Lt=Ne.data?.customers??[],Wt=Le.data?.accounts??[],Dt=Fe.data?.containers??[],is=Pe.data?.workspaces??[],nt=!!k&&!Lt.some(N=>N.customerId===k),ms=!!d&&!Wt.some(N=>N.id===d),wt=!!S&&!Dt.some(N=>N.id===S),hs=!!K&&!is.some(N=>N.id===K),Ot=nt&&Ne.isSuccess&&Ne.data.truncated===!1,Yt=ms&&Le.isSuccess&&Le.data.truncated===!1,Bt=wt&&Fe.isSuccess&&Fe.data.truncated===!1,et=hs&&Pe.isSuccess&&Pe.data.truncated===!1,xs=Yt||Bt||et,Gt=Yt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Bt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":et?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,St=En(Ot,Ne.data,Ne.isError),ps=En(Yt,Le.data,Le.isError),dt=En(Bt,Fe.data,Fe.isError),Zt=En(et,Pe.data,Pe.isError),C=Ne.isError?ut(Ne.error):null,be=Le.isError?ut(Le.error):Fe.isError?ut(Fe.error):Pe.isError?ut(Pe.error):null,ve=u==="google-ads"?C:u==="gtm"?be:null,I=Dn("customer",Ne.data,Lt.length),Q=Dn("account",Le.data,Wt.length),me=Dn("container",Fe.data,Dt.length),te=Dn("draft workspace",Pe.data,is.length),ne=Le.isError||Fe.isError||Pe.isError&&!!K,Ee=m||u!==null||T;function es(){Ne.refetch()}function pt(){if(Le.isError){Le.refetch();return}if(Fe.isError){Fe.refetch();return}Pe.isError&&Pe.refetch()}return ee.isLoading||ie.isLoading||W.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map(N=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"skeleton-text-sm w-full"}),e.jsx("div",{className:"skeleton-text-sm w-3/4"})]},N))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):W.isError&&!W.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",ut(W.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{W.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Wh,{workspace:M,onPrimaryAction:Pt,actionPending:qe,actionError:Ee?null:a,contracts:de,selectedContractId:Ae?.id??null,onSelectContract:N=>ge(N||null),contractError:W.isError?ut(W.error):null,onRetryContracts:()=>{W.refetch()},onRetryEvidence:()=>{Promise.all([se.refetch(),le.refetch()])},onChangeGoogleAdsSelection:Ge,onChangeGtmSelection:bt,onAddContract:()=>Pt("declare-contract")}),r?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:r}):null,m?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:Me(async N=>{N.preventDefault(),await kt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:zt,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:N=>p(N.target.value),className:Ct,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:Qe.isPending,children:Qe.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:Te,children:"Cancel"})]})]})]}):null,u==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),ve?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ve}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:es,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ot?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(qn,{id:"google-ads-customer",label:"Customer account",value:k,onChange:N=>{b(!0),O(N);const re=Lt.find(at=>at.customerId===N);A(re?.parentCustomerId??"")},disabled:Ne.isLoading,children:[e.jsx("option",{value:"",children:Ne.isLoading?"Loading accessible customers…":"Select a customer"}),nt?e.jsxs("option",{value:k,disabled:Ot,children:["Saved customer ",k," (",St,")"]}):null,Lt.map(N=>e.jsx("option",{value:N.customerId,children:N.descriptiveName??`Customer ${N.customerId}`},N.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:zt,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Ct,value:q,onChange:N=>{b(!0),A(N.target.value)},placeholder:"Use only when a manager context is required"})]})]}),I?e.jsx("p",{role:"status",className:`mt-3 text-sm ${Ne.data?.truncated?"text-caution":"text-secondary"}`,children:I}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:we.isPending||Ne.isLoading||Ne.isError||Ot||!k,onClick:Me(At),children:we.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:jt,children:"Cancel"})]}),ee.data?.connected?e.jsx(Yi,{providerLabel:"Google Ads",disabled:qe,onDisconnect:G}):null]}):null,u==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),ve?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ve}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:pt,children:Le.isError?"Retry account list":Fe.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Gt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Gt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(qn,{id:"gtm-account",label:"Account",value:d,onChange:N=>{f(!0),N!==d&&(V(""),w("")),y(N)},disabled:Le.isLoading,children:[e.jsx("option",{value:"",children:Le.isLoading?"Loading accounts…":"Select an account"}),ms?e.jsxs("option",{value:d,disabled:Yt,children:["Saved account ",d," (",ps,")"]}):null,Wt.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]}),e.jsxs(qn,{id:"gtm-container",label:"Container",value:S,onChange:N=>{f(!0),N!==S&&w(""),V(N)},disabled:!d||Fe.isLoading,children:[e.jsx("option",{value:"",children:Fe.isLoading?"Loading containers…":"Select a container"}),wt?e.jsxs("option",{value:S,disabled:Bt,children:["Saved container ",S," (",dt,")"]}):null,Dt.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]}),e.jsxs(qn,{id:"gtm-workspace",label:"Draft workspace (optional)",value:K,onChange:N=>{f(!0),w(N)},disabled:!S||Pe.isLoading,children:[e.jsx("option",{value:"",children:Pe.isLoading?"Loading workspaces…":"No draft workspace"}),hs?e.jsxs("option",{value:K,disabled:et,children:["Saved draft workspace ",K," (",Zt,")"]}):null,is.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[Q?e.jsx("p",{role:"status",className:Le.data?.truncated?"text-caution":"text-secondary",children:Q}):null,me?e.jsx("p",{role:"status",className:Fe.data?.truncated?"text-caution":"text-secondary",children:me}):null,te?e.jsx("p",{role:"status",className:Pe.data?.truncated?"text-caution":"text-secondary",children:te}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:Ze.isPending||Le.isLoading||Fe.isLoading||Pe.isLoading&&!!K||ne||xs||!d||!S,onClick:Me(lt),children:Ze.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:jt,children:"Cancel"})]}),ie.data?.connected?e.jsx(Yi,{providerLabel:"Tag Manager",disabled:qe,onDisconnect:ke}):null]}):null,T?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:Me(async N=>{N.preventDefault(),await ct()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:zt,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Ct,value:$.name,onChange:N=>H(re=>({...re,name:N.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:zt,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Ct,value:$.eventName,onChange:N=>H(re=>({...re,eventName:N.target.value})),placeholder:"booking_complete"})]}),e.jsx(Xi,{id:"contract-conversion-action",label:"Google Ads conversion action",options:R?.googleAds.conversionActions??[],synced:R?.googleAds.syncedAt!=null,loading:B.isLoading,failed:B.isError,onRetry:()=>{B.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:$.conversionActionId,onChange:N=>H(re=>({...re,conversionActionId:N}))}),e.jsx(Xi,{id:"contract-gtm-tag",label:"Tag Manager tag",options:R?.gtm.tags??[],synced:R?.gtm.syncedAt!=null,loading:B.isLoading,failed:B.isError,onRetry:()=>{B.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:$.tagId,onChange:N=>H(re=>({...re,tagId:N}))})]}),e.jsxs("details",{className:"inline-disclosure mt-5 max-w-3xl",children:[e.jsx("summary",{children:"Additional matching rules"}),e.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-conversion-id",className:zt,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Ct,value:$.conversionId,onChange:N=>H(re=>({...re,conversionId:N.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:zt,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Ct,value:$.conversionLabel,onChange:N=>H(re=>({...re,conversionLabel:N.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:zt,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Ct,value:$.triggerIds,onChange:N=>H(re=>({...re,triggerIds:N.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:zt,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Ct,value:$.variableIds,onChange:N=>H(re=>({...re,variableIds:N.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:zt,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Ct,value:$.campaignIds,onChange:N=>H(re=>({...re,campaignIds:N.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:zt,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Ct,value:$.productionHosts,onChange:N=>H(re=>({...re,productionHosts:N.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(Bs,{id:"contract-primary-action",checked:$.requirePrimaryAction,onChange:N=>H(re=>({...re,requirePrimaryAction:N})),children:"Google Ads action is primary"}),e.jsx(Bs,{id:"contract-biddable-goal",checked:$.requireBiddableGoal,onChange:N=>H(re=>({...re,requireBiddableGoal:N})),children:"Google Ads goal is biddable"}),e.jsx(Bs,{id:"contract-runtime-verification",checked:$.verificationRequired,onChange:N=>H(re=>({...re,verificationRequired:N})),children:"Runtime proof is required"}),e.jsx(Bs,{id:"contract-transaction-id",checked:$.requireTransactionId,onChange:N=>H(re=>({...re,requireTransactionId:N})),children:"Transaction ID is required"}),e.jsx(Bs,{id:"contract-value",checked:$.requireValue,onChange:N=>H(re=>({...re,requireValue:N})),children:"Conversion value is required"}),e.jsx(Bs,{id:"contract-currency",checked:$.requireCurrency,onChange:N=>H(re=>({...re,requireCurrency:N})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"submit",disabled:E.isPending,children:E.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:Tt,children:"Cancel"})]})]})]}):null]})}const tx=6e4,sx=["7d","14d","30d"],Qa="not available",nx='Figures come from the stored Google Ads snapshot; this view never calls Google. The window ends on the newest CLOSED day, because the capture day is only partly recorded and would read as a drop. A calendar day the provider returned no row for is zero delivery, so it is charted as zero. Rates with a zero denominator read "not available", never 0%.',ax="No Google Ads snapshot stored yet",ix="Connect a Google Ads account in Conversion Integrity below, choose the customer, then run a Google Ads sync. Spend, clicks, impressions, and conversions appear here once the first snapshot is stored.",rx="No closed days yet",ox="The stored snapshot covers no completed day yet. Figures appear after a full day closes in the account time zone; the day a snapshot is captured is partial and is left out on purpose. If this persists, check the latest Google Ads sync in Activity.",lx={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},ys=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),ya=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),ho=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),cx=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Vs(t,s){return t===null||!Number.isFinite(t)?Qa:s===null?cx.format(t/1e6):vu(t,s)}function ja(t){if(t===null||!Number.isFinite(t))return Qa;const s=t*100;return s>0&&s<.1?"<0.1%":`${ho.format(s)}%`}function dx(t,s){if(t===null||!Number.isFinite(t))return`${Qa} vs prior ${s}d`;if(t===0)return`no change vs prior ${s}d`;const n=Math.abs(t*100),a=n<.1?"<0.1%":`${ho.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function ux(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function mx(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function hx(t,s){return s==="none"||t===null||!Number.isFinite(t)||t===0?"text-muted":(s==="up-good"?t>0:t<0)?"text-positive":"text-negative"}function xx({projectName:t}){const[s,n]=l.useState("14d"),[a,i]=l.useState(()=>new Set(["costMicros","conversions"])),r=Ie({...bc({client:U,path:{name:t},query:{window:s}}),staleTime:tx}),o=r.data,m=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Je,{text:nx})]}),o?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Ut(o.startDate)," to ",Ut(o.endDate)," · ",o.days," closed ",o.days===1?"day":"days"]}):null]}),e.jsx(to,{windows:sx,value:s,onChange:n,label:"Google Ads time period"})]});if(r.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[m,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(d=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},d))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(r.isError||!o)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",ut(r.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{r.refetch()},children:"Retry performance"})]});const{totals:c,daily:h,campaigns:p,comparison:u,comparisonUnavailableReason:v,source:j}=o;if(!j){const d=v==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:d?rx:ax}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:d?ox:ix})]})]})}const b=j.currencyCode,g=j.campaignsInInventory>0&&j.campaignsQueried<j.campaignsInInventory?{queried:j.campaignsQueried,inInventory:j.campaignsInInventory}:null,f=c.costMicros>0&&c.conversions===0,k=[{key:"spend",comparable:!0,label:"Spend",value:Vs(c.costMicros,b),change:u?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:ya.format(c.conversions),change:u?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:f?"no conversions":Vs(c.costPerConversionMicros,b),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:ja(c.conversionRate),change:u?.change.conversionRate??null,direction:"up-good",seriesKey:null}],O=[{key:"clicks",label:"Clicks",value:ys.format(c.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:ys.format(c.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:ja(c.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:Vs(c.cpcMicros,b),seriesKey:null}],q={costMicros:{label:"Spend",color:rt[1],axisId:"spend",formatValue:d=>Vs(d,b)},conversions:{label:"Conversions",color:rt[0],axisId:"conversions",formatValue:d=>ya.format(d)},clicks:{label:"Clicks",color:rt[2],axisId:"clicks",formatValue:d=>ys.format(d)},impressions:{label:"Impressions",color:rt[3],axisId:"impressions",formatValue:d=>ys.format(d)}},A=[...a].map(d=>({dataKey:d,...q[d]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,g!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",ys.format(g.queried)," of"," ",ys.format(g.inInventory)," campaigns, so they are a subset of the account."]}):null,j.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!u&&v==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:lx["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:k.map(d=>{const y=d.seriesKey!==null&&a.has(d.seriesKey),S=y&&a.size===1,V=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[d.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:y?q[d.seriesKey].color:"var(--color-mono-600)"}}):null,d.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:d.value}),u&&d.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${hx(d.change,d.direction)}`,children:dx(d.change,u.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:d.comparable?`no prior ${s} period stored`:" "})]});return d.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:V},d.key):e.jsx("button",{type:"button","aria-pressed":y,disabled:S,onClick:()=>i(K=>{const w=new Set(K);return w.has(d.seriesKey)?w.delete(d.seriesKey):w.add(d.seriesKey),w.size===0?K:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${y?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:V},d.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:O.map(d=>{const y=d.seriesKey!==null&&a.has(d.seriesKey),S=y&&a.size===1,V=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[d.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:y?q[d.seriesKey].color:"var(--color-mono-600)"}}):null,d.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:d.value})]});return d.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:V},d.key):e.jsx("button",{type:"button","aria-pressed":y,disabled:S,onClick:()=>i(K=>{const w=new Set(K);return w.has(d.seriesKey)?w.delete(d.seriesKey):w.add(d.seriesKey),w.size===0?K:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:V},d.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Er,{data:h,xKey:"date",series:A,xTickFormatter:gn,labelFormatter:Ut}),e.jsx("ul",{className:"sr-only",children:h.map(d=>e.jsxs("li",{children:[Ut(d.date),":"," ",A.map(y=>`${y.label} ${q[y.dataKey].formatValue(d[y.dataKey])}`).join(", "),d.origin==="filled"?", no delivery reported":""]},d.date))})]}),e.jsxs("div",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:p.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):p.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:d.name??d.campaignId,children:d.name??e.jsx("span",{className:"font-mono text-secondary",children:d.campaignId})}),e.jsx("td",{children:e.jsx(oe,{tone:ux(d.status),children:mx(d.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ys.format(d.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ys.format(d.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Vs(d.totals.costMicros,b)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ya.format(d.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ja(d.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:d.totals.costMicros>0&&d.totals.conversions===0?e.jsx(oe,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:Vs(d.totals.costPerConversionMicros,b)})})]},d.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Ss(us(j.capturedAt))," · ","customer ",j.customerId," · ","latest closed day ",Ut(j.asOfDate),j.openDate?e.jsxs(e.Fragment,{children:[" · ",Ut(j.openDate)," still open, excluded"]}):null,j.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",j.timeZone]}):null]})]})]})}const Na=20,cs=50,px=50,gx=50;function Ha(t){return t==="viewer"}function Wa(t){return t?.status==="unavailable"}function xo(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function po(t,s){const n=new Map(s.map(i=>[i.id,i.label])),a=t.map(i=>n.get(i)).filter(i=>!!i);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function On(t,s,n){if(t.kind==="all")return s.map(r=>r.id);if(t.kind==="specific")return s.filter(r=>t.propertyIds.includes(r.id)).map(r=>r.id);const a=new Set(t.groupIds),i=new Set(n.filter(r=>a.has(r.id)).flatMap(r=>r.propertyIds));return s.filter(r=>i.has(r.id)).map(r=>r.id)}function fx(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(i=>s.find(r=>r.id===i)?.name).filter(i=>!!i);return a.length===0?"selected groups":a.join(" + ")}function wa(t,s){const n=new Set(s.map(i=>i.id)),a=t.propertyIds.filter(i=>n.has(i)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Ji(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Zi(t){return t==="matched"?"Matched":t==="duplicate"?"Duplicate":t==="ambiguous"?"Ambiguous":t==="proposed"?"Property needs review":t==="excluded"?"Property excluded":t==="invalid"?"Invalid row":"Not matched"}function Gn(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function Fa(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Sa(t){return Fa(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function _a({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:i=!0}){const[r,o]=l.useState(""),[m,c]=l.useState(!1),h=r.trim().toLocaleLowerCase(),p=h?t.filter(b=>b.label.toLocaleLowerCase().includes(h)):t,u=m?p:p.slice(0,px),v=u.length<p.length;function j(){const b=new Set([...s,...u.map(g=>g.id)]);n(t.filter(g=>b.has(g.id)).map(g=>g.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:r,onChange:b=>o(b.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),i?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:u.length===0,onClick:j,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),p.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",u.length," of ",p.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:u.map(b=>{const g=s.includes(b.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${b.label}`,checked:g,type:"checkbox",onChange:f=>n(xo(s,b.id,f.currentTarget.checked))}),e.jsx("span",{children:b.label})]}),b.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[b.urlCount," URLs"]})]},b.id)})}),v?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function Ya(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Xa({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function bx({value:t}){const[s,n]=l.useState(0),[a,i]=l.useState(0),[r,o]=l.useState(null),m=t.preview,c=m?.counts.needsAttention??0,h=m?.rows.filter(S=>S.status==="matched")??[],p=m?.rows??[],u=p.filter(S=>S.status!=="matched"),v=Math.max(1,Math.ceil(p.length/cs)),j=Math.min(s,v-1),b=p.slice(j*cs,(j+1)*cs),g=Math.max(1,Math.ceil(u.length/cs)),f=Math.min(a,g-1),k=u.slice(f*cs,(f+1)*cs),O=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,q=h.length>0&&!t.isApplying,A=m!==null&&r===m.previewChecksum,d=u.length>0&&f===g-1;l.useEffect(()=>{n(0),i(0),o(null)},[m?.previewChecksum]);async function y(S){if(S)try{t.onCsvChange(await S.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:S=>{y(S.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:S=>t.onCsvChange(S.currentTarget.value),placeholder:`property,group,url
|
|
4
4
|
Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!O,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),m?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[m.counts.matchedRows," matched · ",m.counts.groupsReady," group",m.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),m.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:m.groupChanges.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.label}),e.jsx("td",{className:"text-secondary",children:S.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:S.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[S.addedTargetKeys.length,S.unchangedTargetKeys.length>0?` · ${S.unchangedTargetKeys.length} already members`:""]})]},S.groupKey))})]})}):null,m.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",m.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:b.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:Ji(S.status),children:Zi(S.status)}),Gn(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Gn(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",j+1," of ",v," · ",m.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===v-1,onClick:()=>n(S=>Math.min(v-1,S+1)),children:"Next 50 rows"})]})]}):null,c>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",c," row",c===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:k.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:Ji(S.status),children:Zi(S.status)}),Gn(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Gn(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",f+1," of ",g]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===0,onClick:()=>i(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===g-1,onClick:()=>i(S=>Math.min(g-1,S+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:A,disabled:t.isApplying||!d,onChange:S=>o(S.currentTarget.checked?m.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!q||!A,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!q,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${m.counts.groupsReady} group${m.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const vx="—";function yx({access:t,availability:s,properties:n,queries:a,selectedQueryIds:i,isApplying:r=!1,isBusy:o=!1,canContinue:m=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:h,onClearQueryAssignments:p,onRemoveQuery:u,onCreateQueries:v,onCreateAndPairQuestions:j,isCreatingQueries:b=!1,createQueriesError:g=null,onManageProjectQueries:f,groups:k,audience:O,onAudienceChange:q,assignmentImpact:A=null,isPreviewingAssignmentImpact:d=!1,assignmentImpactError:y=null,onRetryAssignmentImpact:S,assignmentNotice:V=null,onReplaceAssignments:K,isReplacingAssignments:w=!1,onBack:T,onContinue:F}){const[$,H]=l.useState(""),[ye,ge]=l.useState(!1),[z,ee]=l.useState(!1),[ie,W]=l.useState(""),[B,R]=l.useState(""),[se,le]=l.useState(null);if(Wa(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Xa,{message:s.message})});const de=Ha(t),X=O,Ae=q,_=On(X,n,k),ae=_.length,Ne=ae>0&&i.length>0&&!r&&!o&&!d&&A!==null&&y===null,Le=p??u,Fe=$.trim().toLocaleLowerCase(),Pe=Fe?a.filter(L=>Sa(L).toLocaleLowerCase().includes(Fe)):a,Qe=Pe.filter(L=>(L.propertyIds?.length??0)===0),ue=z?Qe:Pe,we=ye?ue:ue.slice(0,gx),Ze=we.filter(L=>!Fa(L)),_e=[...new Set(ie.split(`
|