@ainyc/canonry 4.82.0 → 4.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/assets/agent-workspace/skills/aero/SKILL.md +14 -10
  2. package/assets/agent-workspace/skills/aero/references/aeo-discovery.md +7 -5
  3. package/assets/agent-workspace/skills/aero/references/memory-patterns.md +1 -1
  4. package/assets/agent-workspace/skills/aero/references/orchestration.md +22 -20
  5. package/assets/agent-workspace/skills/aero/references/regression-playbook.md +9 -9
  6. package/assets/agent-workspace/skills/aero/references/reporting.md +14 -9
  7. package/assets/agent-workspace/skills/aero/soul.md +5 -5
  8. package/assets/agent-workspace/skills/canonry/SKILL.md +1 -1
  9. package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +84 -36
  10. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +25 -10
  11. package/assets/assets/{BacklinksPage-CHclt-pq.js → BacklinksPage-OrSg_iPA.js} +1 -1
  12. package/assets/assets/{ChartPrimitives-2Ub4vNWe.js → ChartPrimitives-DPBhAT_r.js} +1 -1
  13. package/assets/assets/{ProjectPage-UPmHfuxR.js → ProjectPage-CpMcEmtw.js} +1 -1
  14. package/assets/assets/{RunRow-rUL1UeA3.js → RunRow-2Rty0BAH.js} +1 -1
  15. package/assets/assets/{RunsPage-BQpHfUJf.js → RunsPage-B3ahqf8s.js} +1 -1
  16. package/assets/assets/{SettingsPage-DjTJlr_1.js → SettingsPage-BIjeI85q.js} +1 -1
  17. package/assets/assets/{TrafficPage-D7rv3BrH.js → TrafficPage-DjGoj691.js} +1 -1
  18. package/assets/assets/{TrafficSourceDetailPage-BysyuH2H.js → TrafficSourceDetailPage-BgKG-2q3.js} +1 -1
  19. package/assets/assets/{arrow-left-CR_FGlkE.js → arrow-left-Cf7wmru1.js} +1 -1
  20. package/assets/assets/{extract-error-message-BKkAbWNp.js → extract-error-message-CANxezte.js} +1 -1
  21. package/assets/assets/{index-DzzTt20n.js → index-CGlPx_cu.js} +3 -3
  22. package/assets/assets/{trash-2-uSttujvh.js → trash-2-6nHJZrvy.js} +1 -1
  23. package/assets/index.html +1 -1
  24. package/dist/{chunk-KPSFRSS7.js → chunk-BNF3HXBW.js} +5 -0
  25. package/dist/{chunk-NSZ3D3MM.js → chunk-M3IYKTSF.js} +17 -4
  26. package/dist/{chunk-IEUTAQUF.js → chunk-VJBO4VIK.js} +108 -5
  27. package/dist/{chunk-JLAD6CYH.js → chunk-Y3O3HBMN.js} +1 -1
  28. package/dist/cli.js +22 -16
  29. package/dist/index.js +4 -4
  30. package/dist/{intelligence-service-2UUJ3YGI.js → intelligence-service-PDIAMP5I.js} +2 -2
  31. package/dist/mcp.js +2 -2
  32. package/package.json +9 -9
@@ -1,4 +1,4 @@
1
- import{j as e,r,L as gt,n as bt,u as Pe,o as ss,A as Ai,h as Di}from"./vendor-tanstack-Dq7p98wZ.js";import{c as zs,T as ce,t as Li,a as $i,u as Qn,C as Ii,b as Ss,P as Ot,B as D,h as Pi,d as Ri,e as Ti,f as Xe,g as K,i as X,I as Ce,j as Xt,k as Ei,l as V,m as Mi,n as Bi,o as Oi,p as Fi,q as Kn,r as Gi,s as qi,S as zt,v as _i,w as Ui,x as Qi,y as It,z as Ki,A as pn,D as Vi,G as $e,E as Js,F as Wi,H as Hi,J as Yi,K as Ji,L as Xi,M as ne,N as gn,O as Vn,Q as Zi,R as ea,U as ta,V as sa,W as na,X as ia,Y as aa,Z as ra,_ as ca,$ as la,a0 as oa,a1 as da,a2 as xa,a3 as ma,a4 as js,a5 as ua,a6 as ha,a7 as fn,a8 as pa,a9 as ga,aa as fa,ab as ba,ac as ys,ad as ja,ae as ya,af as va,ag as Na,ah as Vs,ai as wa,aj as za,ak as Sa,al as ka,am as $s,an as Et,ao as Wn,ap as Hn,aq as Ca,ar as Aa,as as Yn,at as Da,au as La,av as $a,aw as Ia,ax as Pa,ay as Ra,az as Jn,aA as Ta,aB as Xn,aC as Ea,aD as Ma,aE as Ba,aF as Oa,aG as Zn,aH as Fa,aI as Ga,aJ as qa,aK as _a,aL as Ua,aM as Qa,aN as Ka,aO as Va,aP as Wa,aQ as Ha,aR as Ya,aS as Ja,aT as Xa,aU as Za,aV as er,aW as tr,aX as sr,aY as Is,aZ as nr,a_ as ir,a$ as bn,b0 as ar,b1 as rr,b2 as cr,b3 as lr,b4 as or,b5 as dr,b6 as xr,b7 as mr,b8 as ur,b9 as hr,ba as jn,bb as pr,bc as gr,bd as fr,be as br,bf as yn,bg as vn,bh as jr,bi as yr,bj as vr,bk as Nr,bl as wr,bm as zr,bn as Sr,bo as kr,bp as Cr,bq as ei,br as ti,bs as Ar,bt as si,bu as Dr,bv as ni,bw as Lr,bx as $r,by as ms,bz as Ir,bA as Pr,bB as Rr,bC as Nn}from"./index-DzzTt20n.js";import{R as Tr}from"./RunRow-rUL1UeA3.js";import{f as Ft,C as ct,a as He,b as St,c as ft,d as qe,e as Ge,g as vs,h as Er,i as Xs,p as Mr}from"./ChartPrimitives-2Ub4vNWe.js";import{u as Br,t as Or,R as Ns,e as Fr}from"./extract-error-message-BKkAbWNp.js";import{R as Gt,C as qt,X as _t,Y as Ut,T as Qt,L as ii,A as Pt,a as Zs,b as Gr,d as en}from"./vendor-recharts-ClRVR6aX.js";import{C as ai,D as ts,a as qr,T as _r}from"./trash-2-uSttujvh.js";import"./vendor-radix-B57xfQbP.js";import"./vendor-markdown-DK7fbRNb.js";const Ur=[["path",{d:"M5 12h14",key:"1ays0h"}]],Qr=zs("minus",Ur);const Kr=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]],Vr=zs("scan-search",Kr);const Wr=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],Hr=zs("unplug",Wr);const Yr=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Jr=zs("upload",Yr),Xr=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function ri(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function ci(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 li(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(ri).map(ci).filter(Boolean)):new Set}function oi(t,s){const n=ri(t).map(ci).filter(Boolean).filter(i=>!Xr.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function Zr(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function ec(t,s){const n=li(t);if(s.length<=1||n.size===0)return[...s];const i=new Set,a=[];for(const l of s){if(l.category!=="content"){a.push(l);continue}const o=oi(Zr(l),n);!o||i.has(o)||(i.add(o),a.push(l))}return a}function tc(t){const s=li(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const l=oi(a.query,s);return!l||i.has(l)?!1:(i.add(l),!0)})}function Ps(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 sc(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Rs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Ps(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Ps(t.prior)} ${s})`:`Flat ${n} (${Ps(t.prior)} ${s})`}function Ws({state:t,label:s}){return e.jsx(ce,{tone:$i(t),children:s??Li(t)})}function wn({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-zinc-600",children:"No data"});const i={cited:"bg-emerald-400","not-cited":"bg-zinc-600",lost:"bg-rose-400",emerging:"bg-amber-400 ring-1 ring-amber-300/60"},a=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),l=new Date(n[n.length-1].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"});return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:a}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,children:n.map((o,u)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[o.citationState]??"bg-zinc-700"} ${o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"ring-1 ring-amber-300/80 ring-offset-1 ring-offset-zinc-950":""}`,title:[o.citationState,new Date(o.createdAt).toLocaleDateString(),o.model?`model ${o.model}`:null,o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"model changed":null].filter(Boolean).join(" — ")},u))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:l})]})}function nc(t){const s=new Map;for(const i of t)for(const a of i.runHistory){const l=s.get(a.createdAt);l?l.states.push(a.citationState):s.set(a.createdAt,{states:[a.citationState],runId:a.runId})}return[...s.entries()].sort(([i],[a])=>i.localeCompare(a)).map(([i,{states:a,runId:l}])=>({runId:l,createdAt:i,citationState:a.includes("cited")?"cited":a.includes("emerging")?"emerging":"not-cited"}))}const ic=320;function zn(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 Sn(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 kn(t,s){const n=s==="mentions"?"mentioned":"cited",i=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const a=t[t.length-1].citationState,l=t[t.length-2].citationState;if(l!=="cited"&&a==="cited")return`Newly ${n}`;if(l==="cited"&&a!=="cited")return"Lost since last run";let o=0;for(let u=t.length-1;u>=0&&t[u].citationState===a;u--)o++;return a==="cited"?o<=1?`${i} in latest run`:`${i} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function ac(t,s){return s==="citations"?t:t.map(n=>({...n,citationState:zn(n,s),runHistory:n.runHistory.map(i=>({...i,citationState:zn(i,s)}))}))}function rc({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=Qn(),[a,l]=r.useState(new Set),[o,u]=r.useState("mentions"),[m,f]=r.useState(n),j=r.useMemo(()=>{const w=ac(t,o),L=new Map;for(const A of w){const M=A.query,E=s?A.location??null:null,v=s?JSON.stringify([M,E]):M,p=L.get(v)??{key:v,phrase:M,location:E,items:[]};p.items.push(A),L.set(v,p)}return[...L.values()]},[t,o,s]),d=w=>{l(L=>{const A=new Set(L);return A.has(w)?A.delete(w):A.add(w),A})},I=o==="mentions"?"mentioned":"cited",S=o==="mentions"?"Mention History":"Citation History",$=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-zinc-500",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",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-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("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-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-zinc-500",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-zinc-400 hover:text-zinc-200",onClick:()=>{l(w=>w.size===j.length?new Set:new Set(j.map(L=>L.key)))},children:a.size===j.length&&j.length>0?"Collapse all":"Expand all"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":m==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>f("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>f("detailed"),children:"Detailed"})]})]})]})]}),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:S}),e.jsx("th",{scope:"col",children:"Change"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:j.map(({key:w,phrase:L,location:A,items:M})=>{const E=a.has(w),v=M.map(P=>P.citationState),p=v.includes("cited")?"cited":v.includes("emerging")?"emerging":v.includes("lost")?"lost":v.every(P=>P==="pending")?"pending":"not-cited",x=nc(M),T=M.filter(P=>P.citationState===Ii.cited||P.citationState==="emerging").length,U=kn(x,o);return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"evidence-phrase-row cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>d(w),onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),d(w))},tabIndex:0,role:"button","aria-expanded":E,children:[e.jsx("td",{children:e.jsx(Ss,{size:14,className:`transition-transform duration-150 text-zinc-500 ${E?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:L}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:A??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:M.map(P=>e.jsx(Ot,{provider:P.provider},P.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{state:p,label:Sn(p,o)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${T} of ${M.length} engines ${$}`,children:[T,"/",M.length]})]})}),e.jsx("td",{children:e.jsx(wn,{history:x})}),e.jsx("td",{className:"evidence-change-cell",children:U}),e.jsx("td",{})]}),E&&M.map(P=>e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"bg-zinc-900/30",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Ot,{provider:P.provider})}),e.jsx("td",{children:e.jsx(Ws,{state:P.citationState,label:Sn(P.citationState,o)})}),e.jsx("td",{children:e.jsx(wn,{history:P.runHistory})}),e.jsx("td",{className:"evidence-change-cell",children:kn(P.runHistory,o)}),e.jsx("td",{children:e.jsx(D,{variant:"ghost",size:"sm",type:"button",onClick:F=>{F.stopPropagation(),i(P.id)},children:"View"})})]}),m==="detailed"&&e.jsxs("tr",{className:"bg-zinc-900/20",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(oc,{item:P,onViewFull:()=>i(P.id)})})]})]},P.id))]},w)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",I==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function cc(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const l=Ri(a);return l.length>=4?[l]:[]}),...t.recommendedCompetitors??[]].filter(a=>a.trim().length>2),i=[];return s.length>0&&i.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&i.push({terms:n,className:"answer-highlight-competitor"}),i}function lc(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 oc({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-zinc-500 italic",children:"No answer text captured for this run."});const{body:i,truncated:a}=lc(t.answerSnippet,ic),l=cc(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-zinc-300",children:Pi(i,l)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-900/60 px-2 py-0.5 text-[11px] text-zinc-300",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-rose-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-rose-900/40 bg-rose-950/30 px-2 py-0.5 text-[11px] text-rose-300",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.competitorDomains.length-4," more"]})]})]}),a&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-emerald-400 hover:text-emerald-300",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function dc({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:i}){if(t.length===0)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No competitors configured. Add competitors to track overlap."});const a=s!=null,l=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"}),l&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const u=i!=null&&i.toLowerCase()===o.domain.toLowerCase(),m=[a?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",u?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:m,onClick:a?()=>s(o.domain):void 0,title:a?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-zinc-100",children:o.domain}),e.jsx("td",{children:e.jsx(ce,{tone:Ti(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-zinc-300 tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-zinc-500 text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),l&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-zinc-500 transition-colors hover:text-rose-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-rose-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:f=>{f.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Cn({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:l,coverageValue:o,note:u,updatedAt:m,active:f,onClick:j}){return e.jsxs("button",{type:"button",onClick:j,className:`surface-card w-full text-left transition-colors ${f?"border-zinc-200 bg-zinc-900/50":"hover:border-zinc-700 hover:bg-zinc-900/40"}`,children:[e.jsxs("div",{className:"section-head",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:t}),e.jsx("h3",{children:s})]}),e.jsx(ce,{tone:i,children:n})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:a}),e.jsx("p",{className:"mt-1 truncate text-sm text-zinc-200",children:l})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Coverage"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:o})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1 text-xs text-zinc-500 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{children:u}),e.jsx("span",{children:m?`Updated ${Xe(m)}`:"No recent sync yet"})]})]})}function us({label:t,value:s,tone:n}){const i=n==="positive"?"text-emerald-400":n==="negative"?"text-rose-400":"text-zinc-200";return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${i}`,children:s})]})}const xc=6,Kt="__other__",Mt="_socialTotal";function mc(t,s=xc){const n=new Map;for(const j of t)n.set(j.source,(n.get(j.source)??0)+j.sessions);const i=[...n.entries()].sort((j,d)=>d[1]!==j[1]?d[1]-j[1]:j[0].localeCompare(d[0])),a=i.slice(0,s),l=new Set(a.map(([j])=>j)),o=Math.max(0,i.length-s),u=new Map;for(const j of t){let d=u.get(j.date);d||(d={date:j.date,[Mt]:0},u.set(j.date,d));const I=l.has(j.source)?j.source:Kt;d[I]=(d[I]??0)+j.sessions,d[Mt]=(d[Mt]??0)+j.sessions}const m=[...u.values()].sort((j,d)=>String(j.date).localeCompare(String(d.date))),f=a.map(([j])=>j);return o>0&&f.push(Kt),{data:m,sources:f,otherCount:o}}function Bt(t){return t.replace(/\+/g," ")}function di(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const uc=["7d","30d","90d","all"],pt=Ge,Hs=qe.textDim,xi=qe.textFaint,Zt=25,hs=50;function ps(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function mi(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 i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function hc({projectName:t}){const{data:s,isLoading:n,isError:i}=Br(t);if(n)return e.jsx(K,{className:"p-5",children:e.jsx("div",{className:"text-sm text-zinc-500",children:"Loading server activity…"})});if(i)return e.jsx(K,{className:"p-5",children:e.jsx("div",{className:"text-sm text-rose-400",children:"Failed to load server activity."})});const a=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-zinc-50",children:"Crawler hits, AI fetches & AI referral sessions"}),e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:["Server-side log evidence of bulk crawlers, on-demand AI user fetches (ChatGPT-User, Perplexity-User), and AI referral sessions — orthogonal to GA4 click-through traffic below."," ",e.jsx(gt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Manage sources →"})]})]})}),a.length===0?e.jsx(K,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-zinc-400",children:["No server traffic source connected yet."," ",e.jsx(gt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})}):e.jsx(K,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-zinc-900/50 text-[10px] uppercase tracking-wide text-zinc-500",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:a.map(l=>e.jsxs("tr",{className:"border-t border-zinc-800/60",children:[e.jsx("td",{className:"px-4 py-3 text-zinc-100",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ce,{tone:Or(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-zinc-400 text-xs",children:l.lastSyncedAt?mi(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(gt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function pc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(hc,{projectName:t}),e.jsx(gc,{projectName:t})]})}function gc({projectName:t}){const s=bt(),[n,i]=r.useState(null),[a,l]=r.useState(null),[o,u]=r.useState(!0),[m,f]=r.useState(!1),[j,d]=r.useState(!1),[I,S]=r.useState(null),[$,w]=r.useState(null),[L,A]=r.useState("sessions"),[M,E]=r.useState("desc"),[v,p]=r.useState("sessions"),[x,T]=r.useState("desc"),[U,P]=r.useState("sessions"),[F,k]=r.useState("desc"),[R,_]=r.useState("sessions"),[z,H]=r.useState("desc"),[oe,he]=r.useState(1),[be,ee]=r.useState([]),[ge,Ne]=r.useState([]),[g,G]=r.useState([]),[Z,le]=r.useState(!1),[ue,Re]=r.useState("30d");async function we(N){u(!0),S(null);try{const O=await s.fetchQuery({...Ei({client:V,path:{name:t}}),staleTime:Xt});if(N.current)return;if(i(O),!O.connected){l(null),ee([]),Ne([]),G([]),u(!1);return}const Q=ue==="all"?void 0:ue,[J,Ze,Ht,ye]=await Promise.all([s.fetchQuery({...Mi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).then(Qe=>Qe),s.fetchQuery({...Bi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).catch(()=>[]),s.fetchQuery({...Oi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).catch(()=>[]),s.fetchQuery({...Fi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).catch(()=>[])]);if(N.current)return;l(J),ee(Ze),Ne(Ht),G(ye),u(!1)}catch(O){if(N.current)return;S(O instanceof Error?O.message:"Failed to load GA4 data"),u(!1)}}r.useEffect(()=>{const N={current:!1};return we(N),()=>{N.current=!0}},[t,ue,s]);async function ae(){f(!0),S(null),w(null);try{const N=await Kn(t);w(`Synced ${N.rowCount.toLocaleString()} page rows, ${N.aiReferralCount.toLocaleString()} AI and ${N.socialReferralCount.toLocaleString()} social referral rows (${N.days} days)`),await s.invalidateQueries({predicate:O=>{const Q=O.queryKey[0];return typeof Q?._id=="string"&&Q._id.startsWith("getApiV1ProjectsByNameGa")}}),await we({current:!1})}catch(N){S(N instanceof Error?N.message:"Sync failed")}finally{f(!1)}}async function te(){d(!0),S(null),w(null);try{await Gi(t),await s.invalidateQueries({predicate:N=>{const O=N.queryKey[0];return typeof O?._id=="string"&&O._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),w("GA4 disconnected")}catch(N){S(N instanceof Error?N.message:"Disconnect failed")}finally{d(!1)}}function je(N){L===N?E(O=>O==="desc"?"asc":"desc"):(A(N),E("desc"))}function ze(N){v===N?T(O=>O==="desc"?"asc":"desc"):(p(N),T("desc"))}function fe(N){U===N?k(O=>O==="desc"?"asc":"desc"):(P(N),k("desc"))}function B(N){he(1),R===N?H(O=>O==="desc"?"asc":"desc"):(_(N),H("desc"))}const q=r.useMemo(()=>a?.topPages?[...a.topPages].sort((N,O)=>{const Q=N[L],J=O[L];return typeof Q=="string"&&typeof J=="string"?M==="asc"?Q.localeCompare(J):J.localeCompare(Q):M==="asc"?Q-J:J-Q}):[],[a?.topPages,L,M]),re=r.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((N,O)=>{const Q=N[v],J=O[v];return typeof Q=="string"&&typeof J=="string"?x==="asc"?Q.localeCompare(J):J.localeCompare(Q):x==="asc"?Q-J:J-Q}):[],[a?.aiReferrals,v,x]),se=r.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((N,O)=>{const Q=N[R],J=O[R];return typeof Q=="string"&&typeof J=="string"?z==="asc"?Q.localeCompare(J):J.localeCompare(Q):z==="asc"?Q-J:J-Q}):[],[a?.aiReferralLandingPages,R,z]),b=Math.max(1,Math.ceil(se.length/hs)),C=Math.min(Math.max(1,oe),b),Ae=(C-1)*hs,Te=r.useMemo(()=>se.slice(Ae,Ae+hs),[se,Ae]),Se=r.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((N,O)=>{const Q=N[U],J=O[U];return typeof Q=="string"&&typeof J=="string"?F==="asc"?Q.localeCompare(J):J.localeCompare(Q):F==="asc"?Q-J:J-Q}):[],[a?.socialReferrals,U,F]),{socialChartData:jt,socialChartSources:lt,socialOtherCount:_e}=r.useMemo(()=>{const N=mc(g);return{socialChartData:N.data,socialChartSources:N.sources,socialOtherCount:N.otherCount}},[g]),{chartData:ot,chartSources:Ee,dateRange:Ye}=r.useMemo(()=>{const N=[...new Set(be.map(ye=>ye.source))],O=new Map;for(const ye of ge)O.set(ye.date,{_totalSessions:ye.sessions,_organicSessions:ye.organicSessions});const Q=new Map;for(const ye of be){const Qe=`${ye.date}::${ye.source}`,At=Q.get(Qe)??0;Q.set(Qe,Math.max(At,ye.sessions))}for(const[ye,Qe]of Q){const[At,xt]=ye.split("::");let et=O.get(At);et||(et={_totalSessions:0,_organicSessions:0},O.set(At,et)),et[xt]=(et[xt]??0)+Qe}const J=[...O.entries()].sort(([ye],[Qe])=>ye.localeCompare(Qe)).map(([ye,Qe])=>({date:ye,...Qe})),Ze=J.map(ye=>ye.date),Ht=Ze.length>0?{start:Ze[0],end:Ze[Ze.length-1]}:null;return{chartData:J,chartSources:N,dateRange:Ht}},[be,ge]);if(o&&!n)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return e.jsx(fc,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:N=>{const O=N.queryKey[0];return typeof O?._id=="string"&&O._id.startsWith("getApiV1ProjectsByNameGa")}}),await we({current:!1})))()}});const tt=a?.organicSharePctDisplay??"0%",yt=a?.channelBreakdown?.organic.sharePctDisplay??tt,kt=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,Vt=a?.aiSessionsDeduped??0,De=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,Oe=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",Fe=a?new Set(a.aiReferrals.map(N=>N.source.toLowerCase())).size:0,dt=re[0]??null,st=a?.totalDirectSessions??0,h=a?.directSharePctDisplay??"0%",W=a?.channelBreakdown?.direct.sessions??st,de=a?.channelBreakdown?.direct.sharePctDisplay??h,Me=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,xe=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",nt=a?.socialSessions??0,is=a?.socialSharePctDisplay??"0%",Wt=a?.channelBreakdown?.social.sessions??nt,Ct=a?.channelBreakdown?.social.sharePctDisplay??is,vt=a?new Set(a.socialReferrals.map(N=>N.source.toLowerCase())).size:0,Ue=Se[0]??null;return e.jsxs(e.Fragment,{children:[I&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:I}),$&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-emerald-900/20 border border-emerald-800/60 text-sm text-emerald-300",children:$}),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-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Property ",e.jsx("span",{className:"text-zinc-300",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-zinc-500",children:n.clientEmail})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(D,{variant:"outline",size:"sm",disabled:m,onClick:X(ae),children:[e.jsx(Ns,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(D,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:j,onClick:X(te),children:[e.jsx(Hr,{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-zinc-500 mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Site Traffic",e.jsx(Ce,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${a?.periodStart&&a?.periodEnd?` Data available: ${new Date(a.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(a.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"flex gap-1",children:uc.map(N=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${ue===N?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>Re(N),children:N==="all"?"All":N},N))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ts,{value:ps(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ts,{value:ps(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${tt} of total`,tone:"positive"}),e.jsx(Ts,{value:ps(a.totalUsers),label:"Total Users",subtitle:a.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-zinc-800/60",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-3",children:"No traffic data yet."}),e.jsxs(D,{variant:"outline",size:"sm",disabled:m,onClick:X(ae),children:[e.jsx(Ns,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),"Sync from GA4"]})]})]}),a&&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-zinc-500 mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ce,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed. Other channels are the remaining GA4 session default channel groups, such as Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, and Paid Other."})]})]}),Ye&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(Ye.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Ye.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),ot.length>0&&e.jsxs(K,{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-zinc-100",children:Ee.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Ee.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Ee.length===0&&e.jsx("p",{className:"text-xs text-zinc-500",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:ot,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(_t,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:ct},tickFormatter:Ft}),e.jsx(Ut,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Qt,{...ft,labelFormatter:St,formatter:(N,O)=>{const Q=typeof N=="number"?N.toLocaleString():String(N??0),J=String(O??"");return J==="_totalSessions"?[Q,"Total Sessions"]:J==="_organicSessions"?[Q,"Organic Sessions"]:[Q,J]}}),e.jsx(ii,{wrapperStyle:{fontSize:11,color:qe.text},formatter:N=>N==="_totalSessions"?"Total Sessions":N==="_organicSessions"?"Organic Sessions":N}),e.jsx(Pt,{type:"monotone",dataKey:"_totalSessions",stroke:qe.textFaint,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ee.map((N,O)=>e.jsx(Pt,{type:"monotone",dataKey:N,stackId:"ai",stroke:pt[O%pt.length],fill:pt[O%pt.length],fillOpacity:.4,strokeWidth:1.5},N))]})})})]}),e.jsxs(K,{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-zinc-100",children:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Je,{label:"Organic",value:yt,hint:`${kt.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(Je,{label:"Social",value:Ct,hint:`${Wt.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(Je,{label:"Direct",value:de,hint:`${W.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(Je,{label:"Known AI referrers (lower bound)",value:Oe,hint:`${De.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). These sessions are removed from their native GA4 channel in this card grid so the five buckets stay disjoint. This is a strict lower bound: most AI traffic strips the referrer and falls into Direct, so the true AI share is typically higher than what's shown here. The detail table below also surfaces firstUserSource and UTM-tagged AI signals."}),e.jsx(Je,{label:"Other channels",value:xe,hint:`${Me.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."})]}),dt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-emerald-800/40 bg-emerald-500/6 px-4 py-3 text-sm text-emerald-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:dt.source})," via ",dt.medium,", accounting for ",dt.sessions.toLocaleString()," sessions."]})]}),e.jsxs(K,{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-zinc-100",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.aiReferrals.length>0?`${Fe} unique sources, ${a.aiReferrals.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(Ie,{label:"Source",sortKey:"source",current:v,dir:x,onSort:ze,align:"left"}),e.jsx(Ie,{label:"Medium",sortKey:"medium",current:v,dir:x,onSort:ze,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:v,dir:x,onSort:ze,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:v,dir:x,onSort:ze,align:"right"})]})}),e.jsx("tbody",{children:re.map(N=>e.jsx(jc,{referral:N,totalSessions:Vt},`${N.source}:${N.medium}:${N.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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(K,{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-zinc-100",children:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:se.length>hs?`${Ae+1}–${Ae+Te.length} of ${se.length} rows`:se.length>0?`${se.length} rows`:"No landing-page rows"})]}),se.length>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-zinc-500",children:[e.jsx(Ie,{label:"Landing Page",sortKey:"landingPage",current:R,dir:z,onSort:B,align:"left"}),e.jsx(Ie,{label:"Source",sortKey:"source",current:R,dir:z,onSort:B,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:R,dir:z,onSort:B,align:"right"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:R,dir:z,onSort:B,align:"right"})]})}),e.jsx("tbody",{children:Te.map(N=>e.jsx(yc,{row:N},`${N.landingPage}:${N.source}:${N.medium}:${N.sourceDimension}`))})]})}),b>1&&e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>he(C-1),disabled:C<=1,className:"text-xs text-zinc-400 hover:text-zinc-200 disabled:opacity-40 disabled:hover:text-zinc-400 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 disabled:hover:border-zinc-800 transition-colors",children:"Previous"}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:["Page ",C," of ",b]}),e.jsx("button",{type:"button",onClick:()=>he(C+1),disabled:C>=b,className:"text-xs text-zinc-400 hover:text-zinc-200 disabled:opacity-40 disabled:hover:text-zinc-400 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 disabled:hover:border-zinc-800 transition-colors",children:"Next"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),a&&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-zinc-500 mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ce,{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."})]})]}),jt.length>0&&e.jsxs(K,{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-zinc-100",children:"Social sessions over time"})]}),_e>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",lt.length-1," sources · ",_e," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:jt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(_t,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:ct},tickFormatter:Ft}),e.jsx(Ut,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Qt,{...ft,labelFormatter:St,formatter:(N,O)=>{const Q=typeof N=="number"?N.toLocaleString():String(N??0),J=String(O??"");if(J===Mt)return[Q,"Total Social"];if(J===Kt){const Ze=`Other (${_e} source${_e===1?"":"s"})`;return[Q,Ze]}return[Q,Bt(J)]}}),e.jsx(Pt,{type:"monotone",dataKey:Mt,stroke:xi,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),lt.map((N,O)=>{const J=N===Kt?Hs:pt[O%pt.length];return e.jsx(Pt,{type:"monotone",dataKey:N,stackId:"social",stroke:J,fill:J,fillOpacity:.4,strokeWidth:1.5},N)})]})})}),e.jsx(Nc,{sources:lt,otherCount:_e})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(K,{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-zinc-100",children:"Social media visits"})]}),a.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Je,{label:"Social Sessions",value:ps(nt),hint:`${nt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Je,{label:"Share of Traffic",value:is,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Je,{label:"Platforms",value:String(vt),hint:`${a.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Ue&&e.jsxs("div",{className:"mt-4 rounded-lg border border-sky-800/40 bg-sky-500/6 px-4 py-3 text-sm text-sky-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-sky-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${Ue.source} via ${Ue.medium}`,children:di(Bt(Ue.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:Ue.medium,children:["via ",Bt(Ue.medium)," · ",Ue.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(Je,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Je,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Je,{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-zinc-800/60 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-400",children:[e.jsx("p",{className:"mb-1.5 text-zinc-300",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-zinc-500",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(K,{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-zinc-100",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.socialReferrals.length>0?Se.length>Zt&&!Z?`Top ${Zt} of ${Se.length}`:`${Se.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(Ie,{label:"Source",sortKey:"source",current:U,dir:F,onSort:fe,align:"left"}),e.jsx(Ie,{label:"Medium",sortKey:"medium",current:U,dir:F,onSort:fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:U,dir:F,onSort:fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:U,dir:F,onSort:fe,align:"right"})]})}),e.jsx("tbody",{children:(Z?Se:Se.slice(0,Zt)).map(N=>e.jsx(vc,{referral:N,totalSessions:nt},`${N.source}:${N.medium}:${N.channelGroup}`))})]})}),Se.length>Zt&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>le(N=>!N),className:"text-xs text-zinc-400 hover:text-zinc-200 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 transition-colors",children:Z?`Show top ${Zt}`:`Show all ${Se.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-zinc-400 mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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."})]})]})]})]})]}),a&&a.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-zinc-500 mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Ce,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-zinc-500",children:[e.jsx(Ie,{label:"Landing Page",sortKey:"landingPage",current:L,dir:M,onSort:je,align:"left"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:L,dir:M,onSort:je,align:"right"}),e.jsx(Ie,{label:"Organic",sortKey:"organicSessions",current:L,dir:M,onSort:je,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:L,dir:M,onSort:je,align:"right"})]})}),e.jsx("tbody",{children:q.map(N=>e.jsx(bc,{page:N},N.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-zinc-500",children:[e.jsx("span",{children:a?.lastSyncedAt?`Last synced ${mi(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function fc({projectName:t,onConnected:s}){const[n,i]=r.useState(""),[a,l]=r.useState(null),[o,u]=r.useState(null),[m,f]=r.useState(!1),[j,d]=r.useState(null),I=r.useRef(null),S=r.useCallback(w=>{const L=w.target.files?.[0];if(!L)return;d(null),l(L.name);const A=new FileReader;A.onload=()=>{const M=A.result;try{const E=JSON.parse(M);if(!E.client_email||!E.private_key){d("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),u(null);return}u(M)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},A.onerror=()=>{d("Failed to read file."),u(null)},A.readAsText(L)},[]);async function $(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!o){d("Please upload a service account key file.");return}f(!0);try{await qi(t,{propertyId:n.trim(),keyJson:o});try{await Kn(t)}catch{}s()}catch(w){d(w instanceof Error?w.message:"Failed to connect GA4")}finally{f(!1)}}return e.jsxs(K,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-50 mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-zinc-400 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."}),j&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:j}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-zinc-400 mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:w=>i(w.target.value),className:"w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 px-3 py-2 text-sm text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:ring-1 focus:ring-zinc-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",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-zinc-400 mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:I,type:"file",accept:".json,application/json",onChange:S,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>I.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 border-dashed px-4 py-3 text-sm text-zinc-400 hover:border-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:[e.jsx(Jr,{className:"w-4 h-4 shrink-0"}),a?e.jsx("span",{className:"text-zinc-200 truncate",children:a}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-zinc-400",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(D,{variant:"default",size:"sm",disabled:m||!n.trim()||!o,onClick:X($),children:m?"Connecting & syncing…":"Connect GA4"})]})}function Ie({label:t,sortKey:s,current:n,dir:i,onSort:a,align:l}){const o=n===s;return e.jsx("th",{className:`py-1 ${l==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-zinc-300 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 rounded",onClick:()=>a(s),"aria-label":`Sort by ${t}${o?` (currently ${i==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:i==="asc"?"↑":"↓"})]})})}const ui={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function Ts({value:t,label:s,subtitle:n,tone:i}){return e.jsxs("div",{className:"rounded-lg bg-zinc-900/30 border border-zinc-800/60 px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${ui[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Je({value:t,label:s,hint:n,tone:i,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1 flex items-center gap-1",children:[s,a&&e.jsx(Ce,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${ui[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function bc({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[s,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}const hi={session:"Session",first_user:"First Visit",manual_utm:"UTM"},pi={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 jc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=hi[t.sourceDimension]??t.sourceDimension,a=pi[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-200 max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-zinc-500 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 border-zinc-700 text-zinc-400",title:a,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function yc({row:t}){const s=hi[t.sourceDimension]??t.sourceDimension,n=pi[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[360px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-zinc-200 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-zinc-700 text-zinc-400",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function vc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Bt(t.source),l=Bt(t.medium);return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 pr-3 text-zinc-200 truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500 truncate",title:t.medium,children:l}),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-zinc-700 text-zinc-400",title:`GA4 channel group: ${t.channelGroup}`,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-sky-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function Nc({sources:t,otherCount:s}){const n=[{key:Mt,color:xi,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===Kt)n.push({key:Kt,color:Hs,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Bt(a);n.push({key:a,color:pt[i%pt.length]??Hs,label:di(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-zinc-400",children:n.map(i=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:i.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:i.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:i.label})]},i.key))})}function wc(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 zc=["7d","30d","90d","all"],gs=500,ut=25;function Sc({projectName:t,refreshNonce:s}){const n=bt(),[i,a]=r.useState(!1),[l,o]=r.useState([]),[u,m]=r.useState([]),[f,j]=r.useState([]),[d,I]=r.useState(null),[S,$]=r.useState([]),[w,L]=r.useState([]),[A,M]=r.useState(null),[E,v]=r.useState(""),[p,x]=r.useState(""),[T,U]=r.useState("30"),[P,F]=r.useState(!1),[k,R]=r.useState("30d"),[_,z]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[H,oe]=r.useState(0),[he,be]=r.useState(!1),[ee,ge]=r.useState(0),[Ne,g]=r.useState(!1),[G,Z]=r.useState(""),[le,ue]=r.useState(!0),[Re,we]=r.useState(!1),[ae,te]=r.useState(!1),[je,ze]=r.useState(!1),[fe,B]=r.useState(!1),[q,re]=r.useState(!1),[se,b]=r.useState(!1),[C,Ae]=r.useState(null),[Te,Se]=r.useState(!1),[jt,lt]=r.useState(!1),[_e,ot]=r.useState(null),[Ee,Ye]=r.useState(""),[tt,yt]=r.useState(!1),[kt,Vt]=r.useState(!1),[De,Oe]=r.useState("indexed"),[Fe,dt]=r.useState(null),st=!!(_.query.trim()||_.page.trim()||Fe),h=Fe!==null,W=r.useMemo(()=>{if(!Fe)return f;const{key:c,dir:y}=Fe;return[...f].sort((Y,ie)=>{const Le=c===zt.CTR?Number.isFinite(Y.ctr)?Y.ctr:0:Y[c],Be=c===zt.CTR?Number.isFinite(ie.ctr)?ie.ctr:0:ie[c];return y==="asc"?Le-Be:Be-Le})},[f,Fe]),[de,Me]=r.useState([]),[xe,nt]=r.useState(null),[is,Wt]=r.useState(1);r.useEffect(()=>{Wt(1)},[C,De,xe]);const Ct=r.useMemo(()=>xe?(C?.reasonGroups??[]).find(c=>c.reason===xe):void 0,[C,xe]),vt=r.useMemo(()=>C?De==="indexed"?C.indexed:De==="deindexed"?C.deindexed:De==="notIndexed"?xe?Ct?.urls??[]:(C.reasonGroups??[]).length===0?C.notIndexed:[]:[]:[],[C,De,xe,Ct]),Ue=Math.max(1,Math.ceil(vt.length/ut)),N=Math.min(Math.max(1,is),Ue),O=(N-1)*ut,Q=vt.length>ut,J=vt.length===0?0:O+1,Ze=Math.min(O+ut,vt.length),Ht=r.useMemo(()=>C?.indexed.slice(O,O+ut)??[],[C,O]),ye=r.useMemo(()=>C?.notIndexed.slice(O,O+ut)??[],[C,O]),Qe=r.useMemo(()=>C?.deindexed.slice(O,O+ut)??[],[C,O]),At=r.useMemo(()=>(Ct?.urls??[]).slice(O,O+ut),[Ct,O]),[xt,et]=r.useState(!1),[an,me]=r.useState(null),[it,as]=r.useState(null),[rn,at]=r.useState(null);function gi(c,y){const Y=Fr(c),ie=wc(Y);ie?(as(ie),me(null)):(as(null),me(Y.message||y))}const ve=l.find(c=>c.connectionType==="gsc"),fi=f.length>0||S.length>0||w.length>0,As=_i(),Yt=Ui(),Ds=Qi();async function cn(c){if(!c){m([]),v("");return}te(!0);try{const{sites:y}=await n.fetchQuery({...na({client:V,path:{name:t}}),staleTime:$e});m(y),v(c.propertyId??y[0]?.siteUrl??""),as(null)}catch(y){m([]),gi(y,"Failed to load Search Console properties")}finally{te(!1)}}async function Dt(c){B(!0);const y=c??H;try{const Y=parseInt(_.limit,10)||20,ie=st?gs:Y+1,Le=st?0:y,Be={limit:String(ie)};_.startDate&&(Be.startDate=_.startDate),_.endDate&&(Be.endDate=_.endDate),_.query&&(Be.query=_.query),_.page&&(Be.page=_.page),Le>0&&(Be.offset=String(Le)),k&&k!=="all"&&!_.startDate&&(Be.window=k);const Ke=await n.fetchQuery({...Wi({client:V,path:{name:t},query:Be}),staleTime:$e});st?(be(!1),j(Ke),ge(Ke.length),g(!0)):(be(Ke.length>Y),j(Ke.slice(0,Y)),ge(0),g(!1))}catch(Y){j([]),be(!1),ge(0),me(Y instanceof Error?Y.message:"Failed to load GSC performance data")}finally{B(!1)}}async function Ls(){try{const c={};_.startDate&&(c.startDate=_.startDate),_.endDate&&(c.endDate=_.endDate),k&&k!=="all"&&!_.startDate&&(c.window=k);const y=await n.fetchQuery({...Hi({client:V,path:{name:t},query:c}),staleTime:$e});I(y)}catch{I(null)}}async function rs(){re(!0);try{const c=G.trim()||void 0,y={limit:"20"};c&&(y.url=c);const[Y,ie]=await Promise.all([n.fetchQuery({...ta({client:V,path:{name:t},query:y}),staleTime:$e}),n.fetchQuery({...sa({client:V,path:{name:t}}),staleTime:$e})]);$(Y),L(ie)}catch(c){$([]),L([]),me(c instanceof Error?c.message:"Failed to load GSC inspection history")}finally{re(!1)}}async function ln(){Se(!0);try{const[c,y]=await Promise.all([n.fetchQuery({...Vn({client:V,path:{name:t}}),staleTime:$e}),n.fetchQuery({...Zi({client:V,path:{name:t}}),staleTime:$e}).catch(()=>[])]);Ae(c),Me(y)}catch(c){Ae(null),Me([]),me(c instanceof Error?c.message:"Failed to load coverage data")}finally{Se(!1)}}async function on(c){et(!0),me(null);try{const y=await gn(t,{urls:c}),{succeeded:Y,failed:ie,total:Le}=y.summary;ne({title:"Indexing requested",detail:ie===0?`${Y} URL${Y!==1?"s":""} submitted for indexing.`:`${Y}/${Le} submitted successfully, ${ie} failed.`,tone:ie===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(y){me(y instanceof Error?y.message:"Failed to request indexing")}finally{et(!1)}}async function bi(){et(!0),me(null);try{const c=await gn(t,{urls:[],allUnindexed:!0}),{succeeded:y,failed:Y,total:ie}=c.summary;ne({title:"Indexing requested",detail:Y===0?`${y} unindexed URL${y!==1?"s":""} submitted for indexing.`:`${y}/${ie} submitted successfully, ${Y} failed.`,tone:Y===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){me(c instanceof Error?c.message:"Failed to request indexing")}finally{et(!1)}}async function cs(){if(Ee.trim()){yt(!0),me(null);try{await Xi(t,"gsc",Ee.trim()),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(y=>y.connectionType==="gsc"?{...y,sitemapUrl:Ee.trim()}:y)),ne({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),Ye("")}catch(c){me(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{yt(!1)}}}async function dn(){me(null);try{const c=await Yt.mutateAsync({projectName:t,projectLabel:t});ot(c.sitemaps),o(y=>y.map(Y=>Y.connectionType==="gsc"?{...Y,sitemapUrl:c.primarySitemapUrl}:Y))}catch{}}async function ji(){lt(!0),me(null);try{const c=await aa(t);n.setQueryData(ra({client:V,path:{name:t}}),c),ot(c.sitemaps),c.sitemaps.length===0&&at("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(c){me(c instanceof Error?c.message:"Failed to list sitemaps")}finally{lt(!1)}}async function xn(){ue(!0),me(null);try{const[c,y]=await Promise.all([Vi().catch(()=>null),n.fetchQuery({...Js({client:V,path:{name:t}}),staleTime:$e}).catch(()=>[])]);a(!!c?.google?.configured),o(y);const Y=y.find(ie=>ie.connectionType==="gsc");await Promise.all([cn(Y),Dt(),Ls(),rs(),ln()])}finally{ue(!1)}}r.useEffect(()=>{xn()},[t,s]),r.useEffect(()=>{oe(0),Dt(0),Ls()},[k]);const mn=r.useRef(!1);r.useEffect(()=>{if(!mn.current){mn.current=!0;return}oe(0),Dt(0)},[h]);async function yi(){if(!i){me("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),me(null),at(null);try{const{authUrl:c}=await Ji(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){me("Unexpected OAuth redirect URL. Please try again.");return}const y=window.open(c,"_blank","width=600,height=700");if(!y){window.location.assign(c);return}at("Finish the Google consent flow in the popup, then close it to refresh this project.");const Y=window.setInterval(()=>{y.closed&&(window.clearInterval(Y),at(null),n.invalidateQueries({predicate:ie=>{const Le=ie.queryKey[0];return typeof Le?._id=="string"&&Le._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),xn())},1e3)}catch(c){me(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{we(!1)}}async function vi(){me(null),at(null);try{await Yi(t,"gsc"),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.filter(y=>y.connectionType!=="gsc")),m([]),v("")}catch(c){me(c instanceof Error?c.message:"Failed to disconnect")}}async function Ni(){if(E){ze(!0),me(null);try{await ia(t,"gsc",E),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(y=>y.connectionType==="gsc"?{...y,propertyId:E}:y)),ne({title:"GSC property updated",detail:`${t} is now linked to ${E}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){me(c instanceof Error?c.message:"Failed to save GSC property")}finally{ze(!1)}}}async function wi(){me(null),at(null);try{await As.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(T,10)||void 0,full:P||void 0}}),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function un(){if(p.trim()){b(!0),me(null),at(null);try{const c=await ea(t,p.trim());await n.invalidateQueries({predicate:y=>{const Y=y.queryKey[0];return typeof Y?._id=="string"&&Y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),M(c),x(""),await rs()}catch(c){me(c instanceof Error?c.message:"Failed to inspect URL")}finally{b(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),it&&e.jsx("div",{className:"mb-3 rounded-lg border border-amber-800/40 bg-amber-950/20 px-3 py-2.5 text-sm text-amber-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-amber-100",children:it.title}),e.jsx("p",{className:"mt-0.5 text-amber-200/90",children:it.message}),(It(it.enableUrl)||It(it.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[It(it.enableUrl)&&e.jsx("a",{href:It(it.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-amber-100 underline decoration-amber-500/50 underline-offset-2 hover:text-amber-50",children:"Enable Search Console API ↗"}),It(it.indexingApiUrl)&&e.jsx("a",{href:It(it.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-amber-100 underline decoration-amber-500/50 underline-offset-2 hover:text-amber-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-amber-400 hover:text-amber-200",onClick:()=>as(null),children:"×"})]})}),an&&e.jsxs("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:[an,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>me(null),children:"×"})]}),rn&&e.jsxs("div",{className:"mb-3 rounded-lg border border-emerald-800/40 bg-emerald-950/20 px-3 py-2 text-sm text-emerald-300",children:[rn,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>at(null),children:"×"})]}),le?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[ve?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-zinc-500",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-emerald-500"}),e.jsx("span",{className:"text-zinc-300",children:"Authorized"})]}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsx("code",{className:"text-zinc-400",children:ve.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Xe(ve.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:X(vi),children:"Disconnect"})]}):e.jsxs(K,{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(ce,{tone:i?"caution":"negative",children:i?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-5",children:[e.jsx("p",{className:"text-sm text-zinc-300",children:i?"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:[i?e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:Re,onClick:X(yi),children:Re?"Opening…":"Connect Google Search Console"}):e.jsx(D,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(gt,{to:"/settings",children:"Open Settings"})}),!i&&e.jsx("p",{className:"text-xs text-zinc-500",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),ve&&!ve.sitemapUrl&&e.jsx("div",{className:"rounded-lg border border-amber-800/40 bg-amber-950/20 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 text-amber-400",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-5 w-5","aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 6a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 6zm0 9a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-amber-300",children:"Set your sitemap URL"}),e.jsx("p",{className:"mt-1 text-xs text-amber-400/70",children:"Canonry uses your sitemap to discover URLs for index coverage inspection. Auto-discover from GSC or enter it manually."}),e.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx(D,{type:"button",size:"sm",disabled:Yt.isPending||!ve.propertyId,onClick:X(dn),children:Yt.isPending?"Discovering…":"Auto-discover from GSC"}),e.jsx("span",{className:"self-center text-xs text-amber-400/60",children:"or enter manually:"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-amber-800/40 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-500 focus:border-amber-600 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Ee,onChange:c=>Ye(c.target.value),onKeyDown:c=>c.key==="Enter"&&void cs()}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:tt||!Ee.trim(),onClick:X(cs),children:tt?"Saving…":"Save sitemap URL"})]})]})]})]})}),(ve||fi)&&e.jsxs(e.Fragment,{children:[e.jsxs(K,{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.jsx("h3",{children:"Index coverage"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&C.notIndexed.length>0&&e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{bi()},children:xt?"Requesting…":`Request indexing (${C.notIndexed.length})`}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{ln()},children:Te?"Loading…":"Refresh coverage"})]})]}),C&&C.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=C.summary.indexed+C.summary.notIndexed,y=c>0?C.summary.indexed/c:0,Y=c>0?C.summary.notIndexed/c:0,ie=54,Le=2*Math.PI*ie,Be=Le*(1-y),Ke=Le*Y,Lt=Le*y;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:ie,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ie,fill:"none",stroke:vs.positiveDeep,strokeWidth:"14",strokeDasharray:Le,strokeDashoffset:Be,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),C.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ie,fill:"none",stroke:qe.textFaint,strokeWidth:"14",strokeDasharray:`${Ke} ${Le-Ke}`,strokeDashoffset:-Lt,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-zinc-50",children:[(y*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-zinc-500 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-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:C.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-zinc-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-zinc-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:C.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:["Not indexed",(C.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-zinc-600",children:["· ",(C.reasonGroups??[]).length," ",(C.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),C.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-zinc-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-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:C.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex gap-1",children:["indexed","notIndexed","deindexed"].map(c=>{const y=c==="indexed"?C.indexed.length:c==="notIndexed"?C.notIndexed.length:C.deindexed.length,Y=c==="indexed"?"Indexed":c==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${De===c?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{Oe(c),nt(null)},children:[Y," (",y,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[De==="indexed"&&C.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:Ht.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.crawlTime?c.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:c.isMobileFriendly===!0?"Yes":c.isMobileFriendly===!1?"No":"—"})]},c.id))})]}),De==="notIndexed"&&!xe&&(C.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:(C.reasonGroups??[]).map(c=>e.jsxs("tr",{className:"cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>nt(c.reason),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),nt(c.reason))},tabIndex:0,role:"button","aria-label":`View ${c.reason} pages`,children:[e.jsx("td",{className:"text-zinc-200",children:c.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.count})]},c.reason))})]}),De==="notIndexed"&&!xe&&(C.reasonGroups??[]).length===0&&C.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:ye.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.coverageState??"Unknown"})]},c.id))})]}),De==="notIndexed"&&xe&&(()=>{const c=(C.reasonGroups??[]).find(y=>y.reason===xe);return c?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-zinc-400 hover:text-zinc-200 transition-colors",onClick:()=>nt(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:c.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[c.count," affected page",c.count!==1?"s":""]})]}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{on(c.urls.map(y=>y.url))},children:xt?"Requesting…":`Request indexing (${c.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:At.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:y.url}),e.jsx("td",{className:"text-zinc-400",children:y.crawlTime?y.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-200 transition-colors",disabled:xt,onClick:()=>{on([y.url])},title:"Request indexing",children:"Index"})})]},y.id))})]})]}):null})(),De==="deindexed"&&C.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:Qe.map((c,y)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.previousState}),e.jsx("td",{className:"text-zinc-400",children:c.currentState}),e.jsx("td",{className:"text-zinc-400",children:c.transitionDate.split("T")[0]})]},`${c.url}-${y}`))})]}),(De==="indexed"&&C.indexed.length===0||De==="notIndexed"&&!xe&&C.notIndexed.length===0||De==="deindexed"&&C.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-zinc-500",children:"No URLs in this category."}),Q&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-zinc-400",children:[e.jsxs("p",{className:"tabular-nums",children:["Showing ",e.jsx("span",{className:"text-zinc-300",children:J.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-zinc-300",children:Ze.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-zinc-300",children:vt.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Wt(c=>Math.max(1,c-1)),disabled:N<=1,"aria-label":"Previous page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:[e.jsx(Er,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-zinc-200",children:N})," of"," ",e.jsx("span",{className:"text-zinc-200",children:Ue})]}),e.jsxs("button",{type:"button",onClick:()=>Wt(c=>Math.min(Ue,c+1)),disabled:N>=Ue,"aria-label":"Next page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:["Next",e.jsx(Ss,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:Te?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(K,{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.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex gap-1",role:"tablist","aria-label":"Performance window",children:zc.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":k===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${k===c?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>R(c),children:c==="all"?"All":c},c))}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:fe,onClick:()=>{oe(0),Dt(0),Ls()},children:fe?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,y=Math.max(...c.map(pe=>pe.impressions),1),{clicks:Y,impressions:ie,ctr:Le}=d.totals,Be=(Le*100).toFixed(1),Ke=700,Lt=220,Ve={top:12,bottom:36,left:48,right:12},zi=Ke-Ve.left-Ve.right,$t=Lt-Ve.top-Ve.bottom,Jt=zi/c.length,ls=Math.max(Math.min(Jt*.35,24),4),hn=Math.max(ls*.15,1),Si=pe=>{if(pe<=0)return 1;const rt=Math.pow(10,Math.floor(Math.log10(pe))),We=pe/rt,mt=We<=1.5?1.5:We<=3?3:We<=5?5:10;return Math.ceil(mt*rt)},os=4,ds=Math.ceil(Si(y)/os)*os,ki=Array.from({length:os+1},(pe,rt)=>ds/os*rt),Ci=pe=>pe>=1e3?`${(pe/1e3).toFixed(pe>=1e4?0:1)}k`:String(pe);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Clicks ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:Y.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-blue-400"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Impressions ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:ie.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[Be,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ke} / ${Lt}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ke} ${Lt}`,className:"h-full w-full",children:[ki.map((pe,rt)=>{const We=Ve.top+$t-pe/ds*$t;return e.jsxs("g",{children:[e.jsx("line",{x1:Ve.left,y1:We,x2:Ke-Ve.right,y2:We,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:Ve.left-6,y:We+3.5,textAnchor:"end",fill:qe.text,fontSize:"10",fontFamily:"inherit",children:Ci(pe)})]},`t-${rt}`)}),c.map((pe,rt)=>{const We=Ve.left+Jt*rt+Jt/2,mt=pe.impressions/ds*$t,xs=pe.clicks/ds*$t;return e.jsxs("g",{children:[e.jsx("title",{children:`${pe.date}
1
+ import{j as e,r,L as gt,n as bt,u as Pe,o as ss,A as Ai,h as Di}from"./vendor-tanstack-Dq7p98wZ.js";import{c as zs,T as ce,t as Li,a as $i,u as Qn,C as Ii,b as Ss,P as Ot,B as D,h as Pi,d as Ri,e as Ti,f as Xe,g as K,i as X,I as Ce,j as Xt,k as Ei,l as V,m as Mi,n as Bi,o as Oi,p as Fi,q as Kn,r as Gi,s as qi,S as zt,v as _i,w as Ui,x as Qi,y as It,z as Ki,A as pn,D as Vi,G as $e,E as Js,F as Wi,H as Hi,J as Yi,K as Ji,L as Xi,M as ne,N as gn,O as Vn,Q as Zi,R as ea,U as ta,V as sa,W as na,X as ia,Y as aa,Z as ra,_ as ca,$ as la,a0 as oa,a1 as da,a2 as xa,a3 as ma,a4 as js,a5 as ua,a6 as ha,a7 as fn,a8 as pa,a9 as ga,aa as fa,ab as ba,ac as ys,ad as ja,ae as ya,af as va,ag as Na,ah as Vs,ai as wa,aj as za,ak as Sa,al as ka,am as $s,an as Et,ao as Wn,ap as Hn,aq as Ca,ar as Aa,as as Yn,at as Da,au as La,av as $a,aw as Ia,ax as Pa,ay as Ra,az as Jn,aA as Ta,aB as Xn,aC as Ea,aD as Ma,aE as Ba,aF as Oa,aG as Zn,aH as Fa,aI as Ga,aJ as qa,aK as _a,aL as Ua,aM as Qa,aN as Ka,aO as Va,aP as Wa,aQ as Ha,aR as Ya,aS as Ja,aT as Xa,aU as Za,aV as er,aW as tr,aX as sr,aY as Is,aZ as nr,a_ as ir,a$ as bn,b0 as ar,b1 as rr,b2 as cr,b3 as lr,b4 as or,b5 as dr,b6 as xr,b7 as mr,b8 as ur,b9 as hr,ba as jn,bb as pr,bc as gr,bd as fr,be as br,bf as yn,bg as vn,bh as jr,bi as yr,bj as vr,bk as Nr,bl as wr,bm as zr,bn as Sr,bo as kr,bp as Cr,bq as ei,br as ti,bs as Ar,bt as si,bu as Dr,bv as ni,bw as Lr,bx as $r,by as ms,bz as Ir,bA as Pr,bB as Rr,bC as Nn}from"./index-CGlPx_cu.js";import{R as Tr}from"./RunRow-2Rty0BAH.js";import{f as Ft,C as ct,a as He,b as St,c as ft,d as qe,e as Ge,g as vs,h as Er,i as Xs,p as Mr}from"./ChartPrimitives-DPBhAT_r.js";import{u as Br,t as Or,R as Ns,e as Fr}from"./extract-error-message-CANxezte.js";import{R as Gt,C as qt,X as _t,Y as Ut,T as Qt,L as ii,A as Pt,a as Zs,b as Gr,d as en}from"./vendor-recharts-ClRVR6aX.js";import{C as ai,D as ts,a as qr,T as _r}from"./trash-2-6nHJZrvy.js";import"./vendor-radix-B57xfQbP.js";import"./vendor-markdown-DK7fbRNb.js";const Ur=[["path",{d:"M5 12h14",key:"1ays0h"}]],Qr=zs("minus",Ur);const Kr=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]],Vr=zs("scan-search",Kr);const Wr=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],Hr=zs("unplug",Wr);const Yr=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Jr=zs("upload",Yr),Xr=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function ri(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function ci(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 li(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(ri).map(ci).filter(Boolean)):new Set}function oi(t,s){const n=ri(t).map(ci).filter(Boolean).filter(i=>!Xr.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function Zr(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function ec(t,s){const n=li(t);if(s.length<=1||n.size===0)return[...s];const i=new Set,a=[];for(const l of s){if(l.category!=="content"){a.push(l);continue}const o=oi(Zr(l),n);!o||i.has(o)||(i.add(o),a.push(l))}return a}function tc(t){const s=li(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const l=oi(a.query,s);return!l||i.has(l)?!1:(i.add(l),!0)})}function Ps(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 sc(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Rs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Ps(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Ps(t.prior)} ${s})`:`Flat ${n} (${Ps(t.prior)} ${s})`}function Ws({state:t,label:s}){return e.jsx(ce,{tone:$i(t),children:s??Li(t)})}function wn({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-zinc-600",children:"No data"});const i={cited:"bg-emerald-400","not-cited":"bg-zinc-600",lost:"bg-rose-400",emerging:"bg-amber-400 ring-1 ring-amber-300/60"},a=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),l=new Date(n[n.length-1].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"});return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:a}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,children:n.map((o,u)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[o.citationState]??"bg-zinc-700"} ${o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"ring-1 ring-amber-300/80 ring-offset-1 ring-offset-zinc-950":""}`,title:[o.citationState,new Date(o.createdAt).toLocaleDateString(),o.model?`model ${o.model}`:null,o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"model changed":null].filter(Boolean).join(" — ")},u))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:l})]})}function nc(t){const s=new Map;for(const i of t)for(const a of i.runHistory){const l=s.get(a.createdAt);l?l.states.push(a.citationState):s.set(a.createdAt,{states:[a.citationState],runId:a.runId})}return[...s.entries()].sort(([i],[a])=>i.localeCompare(a)).map(([i,{states:a,runId:l}])=>({runId:l,createdAt:i,citationState:a.includes("cited")?"cited":a.includes("emerging")?"emerging":"not-cited"}))}const ic=320;function zn(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 Sn(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 kn(t,s){const n=s==="mentions"?"mentioned":"cited",i=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const a=t[t.length-1].citationState,l=t[t.length-2].citationState;if(l!=="cited"&&a==="cited")return`Newly ${n}`;if(l==="cited"&&a!=="cited")return"Lost since last run";let o=0;for(let u=t.length-1;u>=0&&t[u].citationState===a;u--)o++;return a==="cited"?o<=1?`${i} in latest run`:`${i} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function ac(t,s){return s==="citations"?t:t.map(n=>({...n,citationState:zn(n,s),runHistory:n.runHistory.map(i=>({...i,citationState:zn(i,s)}))}))}function rc({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=Qn(),[a,l]=r.useState(new Set),[o,u]=r.useState("mentions"),[m,f]=r.useState(n),j=r.useMemo(()=>{const w=ac(t,o),L=new Map;for(const A of w){const M=A.query,E=s?A.location??null:null,v=s?JSON.stringify([M,E]):M,p=L.get(v)??{key:v,phrase:M,location:E,items:[]};p.items.push(A),L.set(v,p)}return[...L.values()]},[t,o,s]),d=w=>{l(L=>{const A=new Set(L);return A.has(w)?A.delete(w):A.add(w),A})},I=o==="mentions"?"mentioned":"cited",S=o==="mentions"?"Mention History":"Citation History",$=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-zinc-500",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",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-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("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-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-zinc-500",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-zinc-400 hover:text-zinc-200",onClick:()=>{l(w=>w.size===j.length?new Set:new Set(j.map(L=>L.key)))},children:a.size===j.length&&j.length>0?"Collapse all":"Expand all"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":m==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>f("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>f("detailed"),children:"Detailed"})]})]})]})]}),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:S}),e.jsx("th",{scope:"col",children:"Change"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:j.map(({key:w,phrase:L,location:A,items:M})=>{const E=a.has(w),v=M.map(P=>P.citationState),p=v.includes("cited")?"cited":v.includes("emerging")?"emerging":v.includes("lost")?"lost":v.every(P=>P==="pending")?"pending":"not-cited",x=nc(M),T=M.filter(P=>P.citationState===Ii.cited||P.citationState==="emerging").length,U=kn(x,o);return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"evidence-phrase-row cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>d(w),onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),d(w))},tabIndex:0,role:"button","aria-expanded":E,children:[e.jsx("td",{children:e.jsx(Ss,{size:14,className:`transition-transform duration-150 text-zinc-500 ${E?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:L}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:A??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:M.map(P=>e.jsx(Ot,{provider:P.provider},P.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{state:p,label:Sn(p,o)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${T} of ${M.length} engines ${$}`,children:[T,"/",M.length]})]})}),e.jsx("td",{children:e.jsx(wn,{history:x})}),e.jsx("td",{className:"evidence-change-cell",children:U}),e.jsx("td",{})]}),E&&M.map(P=>e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"bg-zinc-900/30",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Ot,{provider:P.provider})}),e.jsx("td",{children:e.jsx(Ws,{state:P.citationState,label:Sn(P.citationState,o)})}),e.jsx("td",{children:e.jsx(wn,{history:P.runHistory})}),e.jsx("td",{className:"evidence-change-cell",children:kn(P.runHistory,o)}),e.jsx("td",{children:e.jsx(D,{variant:"ghost",size:"sm",type:"button",onClick:F=>{F.stopPropagation(),i(P.id)},children:"View"})})]}),m==="detailed"&&e.jsxs("tr",{className:"bg-zinc-900/20",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(oc,{item:P,onViewFull:()=>i(P.id)})})]})]},P.id))]},w)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",I==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function cc(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const l=Ri(a);return l.length>=4?[l]:[]}),...t.recommendedCompetitors??[]].filter(a=>a.trim().length>2),i=[];return s.length>0&&i.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&i.push({terms:n,className:"answer-highlight-competitor"}),i}function lc(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 oc({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-zinc-500 italic",children:"No answer text captured for this run."});const{body:i,truncated:a}=lc(t.answerSnippet,ic),l=cc(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-zinc-300",children:Pi(i,l)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-900/60 px-2 py-0.5 text-[11px] text-zinc-300",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-rose-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-rose-900/40 bg-rose-950/30 px-2 py-0.5 text-[11px] text-rose-300",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.competitorDomains.length-4," more"]})]})]}),a&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-emerald-400 hover:text-emerald-300",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function dc({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:i}){if(t.length===0)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No competitors configured. Add competitors to track overlap."});const a=s!=null,l=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"}),l&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const u=i!=null&&i.toLowerCase()===o.domain.toLowerCase(),m=[a?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",u?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:m,onClick:a?()=>s(o.domain):void 0,title:a?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-zinc-100",children:o.domain}),e.jsx("td",{children:e.jsx(ce,{tone:Ti(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-zinc-300 tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-zinc-500 text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),l&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-zinc-500 transition-colors hover:text-rose-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-rose-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:f=>{f.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Cn({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:l,coverageValue:o,note:u,updatedAt:m,active:f,onClick:j}){return e.jsxs("button",{type:"button",onClick:j,className:`surface-card w-full text-left transition-colors ${f?"border-zinc-200 bg-zinc-900/50":"hover:border-zinc-700 hover:bg-zinc-900/40"}`,children:[e.jsxs("div",{className:"section-head",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:t}),e.jsx("h3",{children:s})]}),e.jsx(ce,{tone:i,children:n})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:a}),e.jsx("p",{className:"mt-1 truncate text-sm text-zinc-200",children:l})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Coverage"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:o})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1 text-xs text-zinc-500 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{children:u}),e.jsx("span",{children:m?`Updated ${Xe(m)}`:"No recent sync yet"})]})]})}function us({label:t,value:s,tone:n}){const i=n==="positive"?"text-emerald-400":n==="negative"?"text-rose-400":"text-zinc-200";return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${i}`,children:s})]})}const xc=6,Kt="__other__",Mt="_socialTotal";function mc(t,s=xc){const n=new Map;for(const j of t)n.set(j.source,(n.get(j.source)??0)+j.sessions);const i=[...n.entries()].sort((j,d)=>d[1]!==j[1]?d[1]-j[1]:j[0].localeCompare(d[0])),a=i.slice(0,s),l=new Set(a.map(([j])=>j)),o=Math.max(0,i.length-s),u=new Map;for(const j of t){let d=u.get(j.date);d||(d={date:j.date,[Mt]:0},u.set(j.date,d));const I=l.has(j.source)?j.source:Kt;d[I]=(d[I]??0)+j.sessions,d[Mt]=(d[Mt]??0)+j.sessions}const m=[...u.values()].sort((j,d)=>String(j.date).localeCompare(String(d.date))),f=a.map(([j])=>j);return o>0&&f.push(Kt),{data:m,sources:f,otherCount:o}}function Bt(t){return t.replace(/\+/g," ")}function di(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const uc=["7d","30d","90d","all"],pt=Ge,Hs=qe.textDim,xi=qe.textFaint,Zt=25,hs=50;function ps(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function mi(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 i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function hc({projectName:t}){const{data:s,isLoading:n,isError:i}=Br(t);if(n)return e.jsx(K,{className:"p-5",children:e.jsx("div",{className:"text-sm text-zinc-500",children:"Loading server activity…"})});if(i)return e.jsx(K,{className:"p-5",children:e.jsx("div",{className:"text-sm text-rose-400",children:"Failed to load server activity."})});const a=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-zinc-50",children:"Crawler hits, AI fetches & AI referral sessions"}),e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:["Server-side log evidence of bulk crawlers, on-demand AI user fetches (ChatGPT-User, Perplexity-User), and AI referral sessions — orthogonal to GA4 click-through traffic below."," ",e.jsx(gt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Manage sources →"})]})]})}),a.length===0?e.jsx(K,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-zinc-400",children:["No server traffic source connected yet."," ",e.jsx(gt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})}):e.jsx(K,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-zinc-900/50 text-[10px] uppercase tracking-wide text-zinc-500",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:a.map(l=>e.jsxs("tr",{className:"border-t border-zinc-800/60",children:[e.jsx("td",{className:"px-4 py-3 text-zinc-100",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ce,{tone:Or(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-zinc-400 text-xs",children:l.lastSyncedAt?mi(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(gt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function pc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(hc,{projectName:t}),e.jsx(gc,{projectName:t})]})}function gc({projectName:t}){const s=bt(),[n,i]=r.useState(null),[a,l]=r.useState(null),[o,u]=r.useState(!0),[m,f]=r.useState(!1),[j,d]=r.useState(!1),[I,S]=r.useState(null),[$,w]=r.useState(null),[L,A]=r.useState("sessions"),[M,E]=r.useState("desc"),[v,p]=r.useState("sessions"),[x,T]=r.useState("desc"),[U,P]=r.useState("sessions"),[F,k]=r.useState("desc"),[R,_]=r.useState("sessions"),[z,H]=r.useState("desc"),[oe,he]=r.useState(1),[be,ee]=r.useState([]),[ge,Ne]=r.useState([]),[g,G]=r.useState([]),[Z,le]=r.useState(!1),[ue,Re]=r.useState("30d");async function we(N){u(!0),S(null);try{const O=await s.fetchQuery({...Ei({client:V,path:{name:t}}),staleTime:Xt});if(N.current)return;if(i(O),!O.connected){l(null),ee([]),Ne([]),G([]),u(!1);return}const Q=ue==="all"?void 0:ue,[J,Ze,Ht,ye]=await Promise.all([s.fetchQuery({...Mi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).then(Qe=>Qe),s.fetchQuery({...Bi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).catch(()=>[]),s.fetchQuery({...Oi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).catch(()=>[]),s.fetchQuery({...Fi({client:V,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:Xt}).catch(()=>[])]);if(N.current)return;l(J),ee(Ze),Ne(Ht),G(ye),u(!1)}catch(O){if(N.current)return;S(O instanceof Error?O.message:"Failed to load GA4 data"),u(!1)}}r.useEffect(()=>{const N={current:!1};return we(N),()=>{N.current=!0}},[t,ue,s]);async function ae(){f(!0),S(null),w(null);try{const N=await Kn(t);w(`Synced ${N.rowCount.toLocaleString()} page rows, ${N.aiReferralCount.toLocaleString()} AI and ${N.socialReferralCount.toLocaleString()} social referral rows (${N.days} days)`),await s.invalidateQueries({predicate:O=>{const Q=O.queryKey[0];return typeof Q?._id=="string"&&Q._id.startsWith("getApiV1ProjectsByNameGa")}}),await we({current:!1})}catch(N){S(N instanceof Error?N.message:"Sync failed")}finally{f(!1)}}async function te(){d(!0),S(null),w(null);try{await Gi(t),await s.invalidateQueries({predicate:N=>{const O=N.queryKey[0];return typeof O?._id=="string"&&O._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),w("GA4 disconnected")}catch(N){S(N instanceof Error?N.message:"Disconnect failed")}finally{d(!1)}}function je(N){L===N?E(O=>O==="desc"?"asc":"desc"):(A(N),E("desc"))}function ze(N){v===N?T(O=>O==="desc"?"asc":"desc"):(p(N),T("desc"))}function fe(N){U===N?k(O=>O==="desc"?"asc":"desc"):(P(N),k("desc"))}function B(N){he(1),R===N?H(O=>O==="desc"?"asc":"desc"):(_(N),H("desc"))}const q=r.useMemo(()=>a?.topPages?[...a.topPages].sort((N,O)=>{const Q=N[L],J=O[L];return typeof Q=="string"&&typeof J=="string"?M==="asc"?Q.localeCompare(J):J.localeCompare(Q):M==="asc"?Q-J:J-Q}):[],[a?.topPages,L,M]),re=r.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((N,O)=>{const Q=N[v],J=O[v];return typeof Q=="string"&&typeof J=="string"?x==="asc"?Q.localeCompare(J):J.localeCompare(Q):x==="asc"?Q-J:J-Q}):[],[a?.aiReferrals,v,x]),se=r.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((N,O)=>{const Q=N[R],J=O[R];return typeof Q=="string"&&typeof J=="string"?z==="asc"?Q.localeCompare(J):J.localeCompare(Q):z==="asc"?Q-J:J-Q}):[],[a?.aiReferralLandingPages,R,z]),b=Math.max(1,Math.ceil(se.length/hs)),C=Math.min(Math.max(1,oe),b),Ae=(C-1)*hs,Te=r.useMemo(()=>se.slice(Ae,Ae+hs),[se,Ae]),Se=r.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((N,O)=>{const Q=N[U],J=O[U];return typeof Q=="string"&&typeof J=="string"?F==="asc"?Q.localeCompare(J):J.localeCompare(Q):F==="asc"?Q-J:J-Q}):[],[a?.socialReferrals,U,F]),{socialChartData:jt,socialChartSources:lt,socialOtherCount:_e}=r.useMemo(()=>{const N=mc(g);return{socialChartData:N.data,socialChartSources:N.sources,socialOtherCount:N.otherCount}},[g]),{chartData:ot,chartSources:Ee,dateRange:Ye}=r.useMemo(()=>{const N=[...new Set(be.map(ye=>ye.source))],O=new Map;for(const ye of ge)O.set(ye.date,{_totalSessions:ye.sessions,_organicSessions:ye.organicSessions});const Q=new Map;for(const ye of be){const Qe=`${ye.date}::${ye.source}`,At=Q.get(Qe)??0;Q.set(Qe,Math.max(At,ye.sessions))}for(const[ye,Qe]of Q){const[At,xt]=ye.split("::");let et=O.get(At);et||(et={_totalSessions:0,_organicSessions:0},O.set(At,et)),et[xt]=(et[xt]??0)+Qe}const J=[...O.entries()].sort(([ye],[Qe])=>ye.localeCompare(Qe)).map(([ye,Qe])=>({date:ye,...Qe})),Ze=J.map(ye=>ye.date),Ht=Ze.length>0?{start:Ze[0],end:Ze[Ze.length-1]}:null;return{chartData:J,chartSources:N,dateRange:Ht}},[be,ge]);if(o&&!n)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return e.jsx(fc,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:N=>{const O=N.queryKey[0];return typeof O?._id=="string"&&O._id.startsWith("getApiV1ProjectsByNameGa")}}),await we({current:!1})))()}});const tt=a?.organicSharePctDisplay??"0%",yt=a?.channelBreakdown?.organic.sharePctDisplay??tt,kt=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,Vt=a?.aiSessionsDeduped??0,De=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,Oe=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",Fe=a?new Set(a.aiReferrals.map(N=>N.source.toLowerCase())).size:0,dt=re[0]??null,st=a?.totalDirectSessions??0,h=a?.directSharePctDisplay??"0%",W=a?.channelBreakdown?.direct.sessions??st,de=a?.channelBreakdown?.direct.sharePctDisplay??h,Me=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,xe=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",nt=a?.socialSessions??0,is=a?.socialSharePctDisplay??"0%",Wt=a?.channelBreakdown?.social.sessions??nt,Ct=a?.channelBreakdown?.social.sharePctDisplay??is,vt=a?new Set(a.socialReferrals.map(N=>N.source.toLowerCase())).size:0,Ue=Se[0]??null;return e.jsxs(e.Fragment,{children:[I&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:I}),$&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-emerald-900/20 border border-emerald-800/60 text-sm text-emerald-300",children:$}),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-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Property ",e.jsx("span",{className:"text-zinc-300",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-zinc-500",children:n.clientEmail})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(D,{variant:"outline",size:"sm",disabled:m,onClick:X(ae),children:[e.jsx(Ns,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(D,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:j,onClick:X(te),children:[e.jsx(Hr,{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-zinc-500 mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Site Traffic",e.jsx(Ce,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${a?.periodStart&&a?.periodEnd?` Data available: ${new Date(a.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(a.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"flex gap-1",children:uc.map(N=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${ue===N?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>Re(N),children:N==="all"?"All":N},N))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ts,{value:ps(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ts,{value:ps(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${tt} of total`,tone:"positive"}),e.jsx(Ts,{value:ps(a.totalUsers),label:"Total Users",subtitle:a.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-zinc-800/60",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-3",children:"No traffic data yet."}),e.jsxs(D,{variant:"outline",size:"sm",disabled:m,onClick:X(ae),children:[e.jsx(Ns,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),"Sync from GA4"]})]})]}),a&&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-zinc-500 mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ce,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed. Other channels are the remaining GA4 session default channel groups, such as Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, and Paid Other."})]})]}),Ye&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(Ye.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Ye.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),ot.length>0&&e.jsxs(K,{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-zinc-100",children:Ee.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Ee.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Ee.length===0&&e.jsx("p",{className:"text-xs text-zinc-500",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:ot,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(_t,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:ct},tickFormatter:Ft}),e.jsx(Ut,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Qt,{...ft,labelFormatter:St,formatter:(N,O)=>{const Q=typeof N=="number"?N.toLocaleString():String(N??0),J=String(O??"");return J==="_totalSessions"?[Q,"Total Sessions"]:J==="_organicSessions"?[Q,"Organic Sessions"]:[Q,J]}}),e.jsx(ii,{wrapperStyle:{fontSize:11,color:qe.text},formatter:N=>N==="_totalSessions"?"Total Sessions":N==="_organicSessions"?"Organic Sessions":N}),e.jsx(Pt,{type:"monotone",dataKey:"_totalSessions",stroke:qe.textFaint,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ee.map((N,O)=>e.jsx(Pt,{type:"monotone",dataKey:N,stackId:"ai",stroke:pt[O%pt.length],fill:pt[O%pt.length],fillOpacity:.4,strokeWidth:1.5},N))]})})})]}),e.jsxs(K,{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-zinc-100",children:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Je,{label:"Organic",value:yt,hint:`${kt.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(Je,{label:"Social",value:Ct,hint:`${Wt.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(Je,{label:"Direct",value:de,hint:`${W.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(Je,{label:"Known AI referrers (lower bound)",value:Oe,hint:`${De.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). These sessions are removed from their native GA4 channel in this card grid so the five buckets stay disjoint. This is a strict lower bound: most AI traffic strips the referrer and falls into Direct, so the true AI share is typically higher than what's shown here. The detail table below also surfaces firstUserSource and UTM-tagged AI signals."}),e.jsx(Je,{label:"Other channels",value:xe,hint:`${Me.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."})]}),dt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-emerald-800/40 bg-emerald-500/6 px-4 py-3 text-sm text-emerald-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:dt.source})," via ",dt.medium,", accounting for ",dt.sessions.toLocaleString()," sessions."]})]}),e.jsxs(K,{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-zinc-100",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.aiReferrals.length>0?`${Fe} unique sources, ${a.aiReferrals.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(Ie,{label:"Source",sortKey:"source",current:v,dir:x,onSort:ze,align:"left"}),e.jsx(Ie,{label:"Medium",sortKey:"medium",current:v,dir:x,onSort:ze,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:v,dir:x,onSort:ze,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:v,dir:x,onSort:ze,align:"right"})]})}),e.jsx("tbody",{children:re.map(N=>e.jsx(jc,{referral:N,totalSessions:Vt},`${N.source}:${N.medium}:${N.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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(K,{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-zinc-100",children:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:se.length>hs?`${Ae+1}–${Ae+Te.length} of ${se.length} rows`:se.length>0?`${se.length} rows`:"No landing-page rows"})]}),se.length>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-zinc-500",children:[e.jsx(Ie,{label:"Landing Page",sortKey:"landingPage",current:R,dir:z,onSort:B,align:"left"}),e.jsx(Ie,{label:"Source",sortKey:"source",current:R,dir:z,onSort:B,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:R,dir:z,onSort:B,align:"right"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:R,dir:z,onSort:B,align:"right"})]})}),e.jsx("tbody",{children:Te.map(N=>e.jsx(yc,{row:N},`${N.landingPage}:${N.source}:${N.medium}:${N.sourceDimension}`))})]})}),b>1&&e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>he(C-1),disabled:C<=1,className:"text-xs text-zinc-400 hover:text-zinc-200 disabled:opacity-40 disabled:hover:text-zinc-400 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 disabled:hover:border-zinc-800 transition-colors",children:"Previous"}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:["Page ",C," of ",b]}),e.jsx("button",{type:"button",onClick:()=>he(C+1),disabled:C>=b,className:"text-xs text-zinc-400 hover:text-zinc-200 disabled:opacity-40 disabled:hover:text-zinc-400 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 disabled:hover:border-zinc-800 transition-colors",children:"Next"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),a&&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-zinc-500 mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ce,{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."})]})]}),jt.length>0&&e.jsxs(K,{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-zinc-100",children:"Social sessions over time"})]}),_e>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",lt.length-1," sources · ",_e," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:jt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(_t,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:ct},tickFormatter:Ft}),e.jsx(Ut,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Qt,{...ft,labelFormatter:St,formatter:(N,O)=>{const Q=typeof N=="number"?N.toLocaleString():String(N??0),J=String(O??"");if(J===Mt)return[Q,"Total Social"];if(J===Kt){const Ze=`Other (${_e} source${_e===1?"":"s"})`;return[Q,Ze]}return[Q,Bt(J)]}}),e.jsx(Pt,{type:"monotone",dataKey:Mt,stroke:xi,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),lt.map((N,O)=>{const J=N===Kt?Hs:pt[O%pt.length];return e.jsx(Pt,{type:"monotone",dataKey:N,stackId:"social",stroke:J,fill:J,fillOpacity:.4,strokeWidth:1.5},N)})]})})}),e.jsx(Nc,{sources:lt,otherCount:_e})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(K,{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-zinc-100",children:"Social media visits"})]}),a.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Je,{label:"Social Sessions",value:ps(nt),hint:`${nt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Je,{label:"Share of Traffic",value:is,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Je,{label:"Platforms",value:String(vt),hint:`${a.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Ue&&e.jsxs("div",{className:"mt-4 rounded-lg border border-sky-800/40 bg-sky-500/6 px-4 py-3 text-sm text-sky-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-sky-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${Ue.source} via ${Ue.medium}`,children:di(Bt(Ue.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:Ue.medium,children:["via ",Bt(Ue.medium)," · ",Ue.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(Je,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Je,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Je,{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-zinc-800/60 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-400",children:[e.jsx("p",{className:"mb-1.5 text-zinc-300",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-zinc-500",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(K,{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-zinc-100",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.socialReferrals.length>0?Se.length>Zt&&!Z?`Top ${Zt} of ${Se.length}`:`${Se.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(Ie,{label:"Source",sortKey:"source",current:U,dir:F,onSort:fe,align:"left"}),e.jsx(Ie,{label:"Medium",sortKey:"medium",current:U,dir:F,onSort:fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:U,dir:F,onSort:fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:U,dir:F,onSort:fe,align:"right"})]})}),e.jsx("tbody",{children:(Z?Se:Se.slice(0,Zt)).map(N=>e.jsx(vc,{referral:N,totalSessions:nt},`${N.source}:${N.medium}:${N.channelGroup}`))})]})}),Se.length>Zt&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>le(N=>!N),className:"text-xs text-zinc-400 hover:text-zinc-200 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 transition-colors",children:Z?`Show top ${Zt}`:`Show all ${Se.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-zinc-400 mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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."})]})]})]})]})]}),a&&a.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-zinc-500 mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Ce,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-zinc-500",children:[e.jsx(Ie,{label:"Landing Page",sortKey:"landingPage",current:L,dir:M,onSort:je,align:"left"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:L,dir:M,onSort:je,align:"right"}),e.jsx(Ie,{label:"Organic",sortKey:"organicSessions",current:L,dir:M,onSort:je,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:L,dir:M,onSort:je,align:"right"})]})}),e.jsx("tbody",{children:q.map(N=>e.jsx(bc,{page:N},N.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-zinc-500",children:[e.jsx("span",{children:a?.lastSyncedAt?`Last synced ${mi(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function fc({projectName:t,onConnected:s}){const[n,i]=r.useState(""),[a,l]=r.useState(null),[o,u]=r.useState(null),[m,f]=r.useState(!1),[j,d]=r.useState(null),I=r.useRef(null),S=r.useCallback(w=>{const L=w.target.files?.[0];if(!L)return;d(null),l(L.name);const A=new FileReader;A.onload=()=>{const M=A.result;try{const E=JSON.parse(M);if(!E.client_email||!E.private_key){d("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),u(null);return}u(M)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},A.onerror=()=>{d("Failed to read file."),u(null)},A.readAsText(L)},[]);async function $(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!o){d("Please upload a service account key file.");return}f(!0);try{await qi(t,{propertyId:n.trim(),keyJson:o});try{await Kn(t)}catch{}s()}catch(w){d(w instanceof Error?w.message:"Failed to connect GA4")}finally{f(!1)}}return e.jsxs(K,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-50 mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-zinc-400 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."}),j&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:j}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-zinc-400 mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:w=>i(w.target.value),className:"w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 px-3 py-2 text-sm text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:ring-1 focus:ring-zinc-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",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-zinc-400 mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:I,type:"file",accept:".json,application/json",onChange:S,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>I.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 border-dashed px-4 py-3 text-sm text-zinc-400 hover:border-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:[e.jsx(Jr,{className:"w-4 h-4 shrink-0"}),a?e.jsx("span",{className:"text-zinc-200 truncate",children:a}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-zinc-400",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(D,{variant:"default",size:"sm",disabled:m||!n.trim()||!o,onClick:X($),children:m?"Connecting & syncing…":"Connect GA4"})]})}function Ie({label:t,sortKey:s,current:n,dir:i,onSort:a,align:l}){const o=n===s;return e.jsx("th",{className:`py-1 ${l==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-zinc-300 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 rounded",onClick:()=>a(s),"aria-label":`Sort by ${t}${o?` (currently ${i==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:i==="asc"?"↑":"↓"})]})})}const ui={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function Ts({value:t,label:s,subtitle:n,tone:i}){return e.jsxs("div",{className:"rounded-lg bg-zinc-900/30 border border-zinc-800/60 px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${ui[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Je({value:t,label:s,hint:n,tone:i,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1 flex items-center gap-1",children:[s,a&&e.jsx(Ce,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${ui[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function bc({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[s,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}const hi={session:"Session",first_user:"First Visit",manual_utm:"UTM"},pi={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 jc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=hi[t.sourceDimension]??t.sourceDimension,a=pi[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-200 max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-zinc-500 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 border-zinc-700 text-zinc-400",title:a,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function yc({row:t}){const s=hi[t.sourceDimension]??t.sourceDimension,n=pi[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[360px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-zinc-200 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-zinc-700 text-zinc-400",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function vc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Bt(t.source),l=Bt(t.medium);return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 pr-3 text-zinc-200 truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500 truncate",title:t.medium,children:l}),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-zinc-700 text-zinc-400",title:`GA4 channel group: ${t.channelGroup}`,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-sky-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function Nc({sources:t,otherCount:s}){const n=[{key:Mt,color:xi,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===Kt)n.push({key:Kt,color:Hs,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Bt(a);n.push({key:a,color:pt[i%pt.length]??Hs,label:di(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-zinc-400",children:n.map(i=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:i.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:i.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:i.label})]},i.key))})}function wc(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 zc=["7d","30d","90d","all"],gs=500,ut=25;function Sc({projectName:t,refreshNonce:s}){const n=bt(),[i,a]=r.useState(!1),[l,o]=r.useState([]),[u,m]=r.useState([]),[f,j]=r.useState([]),[d,I]=r.useState(null),[S,$]=r.useState([]),[w,L]=r.useState([]),[A,M]=r.useState(null),[E,v]=r.useState(""),[p,x]=r.useState(""),[T,U]=r.useState("30"),[P,F]=r.useState(!1),[k,R]=r.useState("30d"),[_,z]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[H,oe]=r.useState(0),[he,be]=r.useState(!1),[ee,ge]=r.useState(0),[Ne,g]=r.useState(!1),[G,Z]=r.useState(""),[le,ue]=r.useState(!0),[Re,we]=r.useState(!1),[ae,te]=r.useState(!1),[je,ze]=r.useState(!1),[fe,B]=r.useState(!1),[q,re]=r.useState(!1),[se,b]=r.useState(!1),[C,Ae]=r.useState(null),[Te,Se]=r.useState(!1),[jt,lt]=r.useState(!1),[_e,ot]=r.useState(null),[Ee,Ye]=r.useState(""),[tt,yt]=r.useState(!1),[kt,Vt]=r.useState(!1),[De,Oe]=r.useState("indexed"),[Fe,dt]=r.useState(null),st=!!(_.query.trim()||_.page.trim()||Fe),h=Fe!==null,W=r.useMemo(()=>{if(!Fe)return f;const{key:c,dir:y}=Fe;return[...f].sort((Y,ie)=>{const Le=c===zt.CTR?Number.isFinite(Y.ctr)?Y.ctr:0:Y[c],Be=c===zt.CTR?Number.isFinite(ie.ctr)?ie.ctr:0:ie[c];return y==="asc"?Le-Be:Be-Le})},[f,Fe]),[de,Me]=r.useState([]),[xe,nt]=r.useState(null),[is,Wt]=r.useState(1);r.useEffect(()=>{Wt(1)},[C,De,xe]);const Ct=r.useMemo(()=>xe?(C?.reasonGroups??[]).find(c=>c.reason===xe):void 0,[C,xe]),vt=r.useMemo(()=>C?De==="indexed"?C.indexed:De==="deindexed"?C.deindexed:De==="notIndexed"?xe?Ct?.urls??[]:(C.reasonGroups??[]).length===0?C.notIndexed:[]:[]:[],[C,De,xe,Ct]),Ue=Math.max(1,Math.ceil(vt.length/ut)),N=Math.min(Math.max(1,is),Ue),O=(N-1)*ut,Q=vt.length>ut,J=vt.length===0?0:O+1,Ze=Math.min(O+ut,vt.length),Ht=r.useMemo(()=>C?.indexed.slice(O,O+ut)??[],[C,O]),ye=r.useMemo(()=>C?.notIndexed.slice(O,O+ut)??[],[C,O]),Qe=r.useMemo(()=>C?.deindexed.slice(O,O+ut)??[],[C,O]),At=r.useMemo(()=>(Ct?.urls??[]).slice(O,O+ut),[Ct,O]),[xt,et]=r.useState(!1),[an,me]=r.useState(null),[it,as]=r.useState(null),[rn,at]=r.useState(null);function gi(c,y){const Y=Fr(c),ie=wc(Y);ie?(as(ie),me(null)):(as(null),me(Y.message||y))}const ve=l.find(c=>c.connectionType==="gsc"),fi=f.length>0||S.length>0||w.length>0,As=_i(),Yt=Ui(),Ds=Qi();async function cn(c){if(!c){m([]),v("");return}te(!0);try{const{sites:y}=await n.fetchQuery({...na({client:V,path:{name:t}}),staleTime:$e});m(y),v(c.propertyId??y[0]?.siteUrl??""),as(null)}catch(y){m([]),gi(y,"Failed to load Search Console properties")}finally{te(!1)}}async function Dt(c){B(!0);const y=c??H;try{const Y=parseInt(_.limit,10)||20,ie=st?gs:Y+1,Le=st?0:y,Be={limit:String(ie)};_.startDate&&(Be.startDate=_.startDate),_.endDate&&(Be.endDate=_.endDate),_.query&&(Be.query=_.query),_.page&&(Be.page=_.page),Le>0&&(Be.offset=String(Le)),k&&k!=="all"&&!_.startDate&&(Be.window=k);const Ke=await n.fetchQuery({...Wi({client:V,path:{name:t},query:Be}),staleTime:$e});st?(be(!1),j(Ke),ge(Ke.length),g(!0)):(be(Ke.length>Y),j(Ke.slice(0,Y)),ge(0),g(!1))}catch(Y){j([]),be(!1),ge(0),me(Y instanceof Error?Y.message:"Failed to load GSC performance data")}finally{B(!1)}}async function Ls(){try{const c={};_.startDate&&(c.startDate=_.startDate),_.endDate&&(c.endDate=_.endDate),k&&k!=="all"&&!_.startDate&&(c.window=k);const y=await n.fetchQuery({...Hi({client:V,path:{name:t},query:c}),staleTime:$e});I(y)}catch{I(null)}}async function rs(){re(!0);try{const c=G.trim()||void 0,y={limit:"20"};c&&(y.url=c);const[Y,ie]=await Promise.all([n.fetchQuery({...ta({client:V,path:{name:t},query:y}),staleTime:$e}),n.fetchQuery({...sa({client:V,path:{name:t}}),staleTime:$e})]);$(Y),L(ie)}catch(c){$([]),L([]),me(c instanceof Error?c.message:"Failed to load GSC inspection history")}finally{re(!1)}}async function ln(){Se(!0);try{const[c,y]=await Promise.all([n.fetchQuery({...Vn({client:V,path:{name:t}}),staleTime:$e}),n.fetchQuery({...Zi({client:V,path:{name:t}}),staleTime:$e}).catch(()=>[])]);Ae(c),Me(y)}catch(c){Ae(null),Me([]),me(c instanceof Error?c.message:"Failed to load coverage data")}finally{Se(!1)}}async function on(c){et(!0),me(null);try{const y=await gn(t,{urls:c}),{succeeded:Y,failed:ie,total:Le}=y.summary;ne({title:"Indexing requested",detail:ie===0?`${Y} URL${Y!==1?"s":""} submitted for indexing.`:`${Y}/${Le} submitted successfully, ${ie} failed.`,tone:ie===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(y){me(y instanceof Error?y.message:"Failed to request indexing")}finally{et(!1)}}async function bi(){et(!0),me(null);try{const c=await gn(t,{urls:[],allUnindexed:!0}),{succeeded:y,failed:Y,total:ie}=c.summary;ne({title:"Indexing requested",detail:Y===0?`${y} unindexed URL${y!==1?"s":""} submitted for indexing.`:`${y}/${ie} submitted successfully, ${Y} failed.`,tone:Y===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){me(c instanceof Error?c.message:"Failed to request indexing")}finally{et(!1)}}async function cs(){if(Ee.trim()){yt(!0),me(null);try{await Xi(t,"gsc",Ee.trim()),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(y=>y.connectionType==="gsc"?{...y,sitemapUrl:Ee.trim()}:y)),ne({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),Ye("")}catch(c){me(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{yt(!1)}}}async function dn(){me(null);try{const c=await Yt.mutateAsync({projectName:t,projectLabel:t});ot(c.sitemaps),o(y=>y.map(Y=>Y.connectionType==="gsc"?{...Y,sitemapUrl:c.primarySitemapUrl}:Y))}catch{}}async function ji(){lt(!0),me(null);try{const c=await aa(t);n.setQueryData(ra({client:V,path:{name:t}}),c),ot(c.sitemaps),c.sitemaps.length===0&&at("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(c){me(c instanceof Error?c.message:"Failed to list sitemaps")}finally{lt(!1)}}async function xn(){ue(!0),me(null);try{const[c,y]=await Promise.all([Vi().catch(()=>null),n.fetchQuery({...Js({client:V,path:{name:t}}),staleTime:$e}).catch(()=>[])]);a(!!c?.google?.configured),o(y);const Y=y.find(ie=>ie.connectionType==="gsc");await Promise.all([cn(Y),Dt(),Ls(),rs(),ln()])}finally{ue(!1)}}r.useEffect(()=>{xn()},[t,s]),r.useEffect(()=>{oe(0),Dt(0),Ls()},[k]);const mn=r.useRef(!1);r.useEffect(()=>{if(!mn.current){mn.current=!0;return}oe(0),Dt(0)},[h]);async function yi(){if(!i){me("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),me(null),at(null);try{const{authUrl:c}=await Ji(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){me("Unexpected OAuth redirect URL. Please try again.");return}const y=window.open(c,"_blank","width=600,height=700");if(!y){window.location.assign(c);return}at("Finish the Google consent flow in the popup, then close it to refresh this project.");const Y=window.setInterval(()=>{y.closed&&(window.clearInterval(Y),at(null),n.invalidateQueries({predicate:ie=>{const Le=ie.queryKey[0];return typeof Le?._id=="string"&&Le._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),xn())},1e3)}catch(c){me(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{we(!1)}}async function vi(){me(null),at(null);try{await Yi(t,"gsc"),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.filter(y=>y.connectionType!=="gsc")),m([]),v("")}catch(c){me(c instanceof Error?c.message:"Failed to disconnect")}}async function Ni(){if(E){ze(!0),me(null);try{await ia(t,"gsc",E),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(y=>y.connectionType==="gsc"?{...y,propertyId:E}:y)),ne({title:"GSC property updated",detail:`${t} is now linked to ${E}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){me(c instanceof Error?c.message:"Failed to save GSC property")}finally{ze(!1)}}}async function wi(){me(null),at(null);try{await As.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(T,10)||void 0,full:P||void 0}}),await n.invalidateQueries({predicate:c=>{const y=c.queryKey[0];return typeof y?._id=="string"&&y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function un(){if(p.trim()){b(!0),me(null),at(null);try{const c=await ea(t,p.trim());await n.invalidateQueries({predicate:y=>{const Y=y.queryKey[0];return typeof Y?._id=="string"&&Y._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),M(c),x(""),await rs()}catch(c){me(c instanceof Error?c.message:"Failed to inspect URL")}finally{b(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),it&&e.jsx("div",{className:"mb-3 rounded-lg border border-amber-800/40 bg-amber-950/20 px-3 py-2.5 text-sm text-amber-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-amber-100",children:it.title}),e.jsx("p",{className:"mt-0.5 text-amber-200/90",children:it.message}),(It(it.enableUrl)||It(it.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[It(it.enableUrl)&&e.jsx("a",{href:It(it.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-amber-100 underline decoration-amber-500/50 underline-offset-2 hover:text-amber-50",children:"Enable Search Console API ↗"}),It(it.indexingApiUrl)&&e.jsx("a",{href:It(it.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-amber-100 underline decoration-amber-500/50 underline-offset-2 hover:text-amber-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-amber-400 hover:text-amber-200",onClick:()=>as(null),children:"×"})]})}),an&&e.jsxs("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:[an,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>me(null),children:"×"})]}),rn&&e.jsxs("div",{className:"mb-3 rounded-lg border border-emerald-800/40 bg-emerald-950/20 px-3 py-2 text-sm text-emerald-300",children:[rn,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>at(null),children:"×"})]}),le?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[ve?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-zinc-500",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-emerald-500"}),e.jsx("span",{className:"text-zinc-300",children:"Authorized"})]}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsx("code",{className:"text-zinc-400",children:ve.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Xe(ve.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:X(vi),children:"Disconnect"})]}):e.jsxs(K,{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(ce,{tone:i?"caution":"negative",children:i?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-5",children:[e.jsx("p",{className:"text-sm text-zinc-300",children:i?"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:[i?e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:Re,onClick:X(yi),children:Re?"Opening…":"Connect Google Search Console"}):e.jsx(D,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(gt,{to:"/settings",children:"Open Settings"})}),!i&&e.jsx("p",{className:"text-xs text-zinc-500",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),ve&&!ve.sitemapUrl&&e.jsx("div",{className:"rounded-lg border border-amber-800/40 bg-amber-950/20 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 text-amber-400",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-5 w-5","aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 6a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 6zm0 9a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-amber-300",children:"Set your sitemap URL"}),e.jsx("p",{className:"mt-1 text-xs text-amber-400/70",children:"Canonry uses your sitemap to discover URLs for index coverage inspection. Auto-discover from GSC or enter it manually."}),e.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx(D,{type:"button",size:"sm",disabled:Yt.isPending||!ve.propertyId,onClick:X(dn),children:Yt.isPending?"Discovering…":"Auto-discover from GSC"}),e.jsx("span",{className:"self-center text-xs text-amber-400/60",children:"or enter manually:"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-amber-800/40 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-500 focus:border-amber-600 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Ee,onChange:c=>Ye(c.target.value),onKeyDown:c=>c.key==="Enter"&&void cs()}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:tt||!Ee.trim(),onClick:X(cs),children:tt?"Saving…":"Save sitemap URL"})]})]})]})]})}),(ve||fi)&&e.jsxs(e.Fragment,{children:[e.jsxs(K,{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.jsx("h3",{children:"Index coverage"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C&&C.notIndexed.length>0&&e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{bi()},children:xt?"Requesting…":`Request indexing (${C.notIndexed.length})`}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{ln()},children:Te?"Loading…":"Refresh coverage"})]})]}),C&&C.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=C.summary.indexed+C.summary.notIndexed,y=c>0?C.summary.indexed/c:0,Y=c>0?C.summary.notIndexed/c:0,ie=54,Le=2*Math.PI*ie,Be=Le*(1-y),Ke=Le*Y,Lt=Le*y;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:ie,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ie,fill:"none",stroke:vs.positiveDeep,strokeWidth:"14",strokeDasharray:Le,strokeDashoffset:Be,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),C.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ie,fill:"none",stroke:qe.textFaint,strokeWidth:"14",strokeDasharray:`${Ke} ${Le-Ke}`,strokeDashoffset:-Lt,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-zinc-50",children:[(y*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-zinc-500 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-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:C.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-zinc-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-zinc-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:C.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:["Not indexed",(C.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-zinc-600",children:["· ",(C.reasonGroups??[]).length," ",(C.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),C.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-zinc-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-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:C.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex gap-1",children:["indexed","notIndexed","deindexed"].map(c=>{const y=c==="indexed"?C.indexed.length:c==="notIndexed"?C.notIndexed.length:C.deindexed.length,Y=c==="indexed"?"Indexed":c==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${De===c?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{Oe(c),nt(null)},children:[Y," (",y,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[De==="indexed"&&C.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:Ht.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.crawlTime?c.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:c.isMobileFriendly===!0?"Yes":c.isMobileFriendly===!1?"No":"—"})]},c.id))})]}),De==="notIndexed"&&!xe&&(C.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:(C.reasonGroups??[]).map(c=>e.jsxs("tr",{className:"cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>nt(c.reason),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),nt(c.reason))},tabIndex:0,role:"button","aria-label":`View ${c.reason} pages`,children:[e.jsx("td",{className:"text-zinc-200",children:c.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.count})]},c.reason))})]}),De==="notIndexed"&&!xe&&(C.reasonGroups??[]).length===0&&C.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:ye.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.coverageState??"Unknown"})]},c.id))})]}),De==="notIndexed"&&xe&&(()=>{const c=(C.reasonGroups??[]).find(y=>y.reason===xe);return c?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-zinc-400 hover:text-zinc-200 transition-colors",onClick:()=>nt(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:c.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[c.count," affected page",c.count!==1?"s":""]})]}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{on(c.urls.map(y=>y.url))},children:xt?"Requesting…":`Request indexing (${c.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:At.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:y.url}),e.jsx("td",{className:"text-zinc-400",children:y.crawlTime?y.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-200 transition-colors",disabled:xt,onClick:()=>{on([y.url])},title:"Request indexing",children:"Index"})})]},y.id))})]})]}):null})(),De==="deindexed"&&C.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:Qe.map((c,y)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.previousState}),e.jsx("td",{className:"text-zinc-400",children:c.currentState}),e.jsx("td",{className:"text-zinc-400",children:c.transitionDate.split("T")[0]})]},`${c.url}-${y}`))})]}),(De==="indexed"&&C.indexed.length===0||De==="notIndexed"&&!xe&&C.notIndexed.length===0||De==="deindexed"&&C.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-zinc-500",children:"No URLs in this category."}),Q&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-zinc-400",children:[e.jsxs("p",{className:"tabular-nums",children:["Showing ",e.jsx("span",{className:"text-zinc-300",children:J.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-zinc-300",children:Ze.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-zinc-300",children:vt.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Wt(c=>Math.max(1,c-1)),disabled:N<=1,"aria-label":"Previous page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:[e.jsx(Er,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-zinc-200",children:N})," of"," ",e.jsx("span",{className:"text-zinc-200",children:Ue})]}),e.jsxs("button",{type:"button",onClick:()=>Wt(c=>Math.min(Ue,c+1)),disabled:N>=Ue,"aria-label":"Next page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:["Next",e.jsx(Ss,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:Te?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(K,{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.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex gap-1",role:"tablist","aria-label":"Performance window",children:zc.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":k===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${k===c?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>R(c),children:c==="all"?"All":c},c))}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:fe,onClick:()=>{oe(0),Dt(0),Ls()},children:fe?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,y=Math.max(...c.map(pe=>pe.impressions),1),{clicks:Y,impressions:ie,ctr:Le}=d.totals,Be=(Le*100).toFixed(1),Ke=700,Lt=220,Ve={top:12,bottom:36,left:48,right:12},zi=Ke-Ve.left-Ve.right,$t=Lt-Ve.top-Ve.bottom,Jt=zi/c.length,ls=Math.max(Math.min(Jt*.35,24),4),hn=Math.max(ls*.15,1),Si=pe=>{if(pe<=0)return 1;const rt=Math.pow(10,Math.floor(Math.log10(pe))),We=pe/rt,mt=We<=1.5?1.5:We<=3?3:We<=5?5:10;return Math.ceil(mt*rt)},os=4,ds=Math.ceil(Si(y)/os)*os,ki=Array.from({length:os+1},(pe,rt)=>ds/os*rt),Ci=pe=>pe>=1e3?`${(pe/1e3).toFixed(pe>=1e4?0:1)}k`:String(pe);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Clicks ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:Y.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-blue-400"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Impressions ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:ie.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[Be,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ke} / ${Lt}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ke} ${Lt}`,className:"h-full w-full",children:[ki.map((pe,rt)=>{const We=Ve.top+$t-pe/ds*$t;return e.jsxs("g",{children:[e.jsx("line",{x1:Ve.left,y1:We,x2:Ke-Ve.right,y2:We,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:Ve.left-6,y:We+3.5,textAnchor:"end",fill:qe.text,fontSize:"10",fontFamily:"inherit",children:Ci(pe)})]},`t-${rt}`)}),c.map((pe,rt)=>{const We=Ve.left+Jt*rt+Jt/2,mt=pe.impressions/ds*$t,xs=pe.clicks/ds*$t;return e.jsxs("g",{children:[e.jsx("title",{children:`${pe.date}
2
2
  Clicks: ${pe.clicks}
3
3
  Impressions: ${pe.impressions}
4
4
  CTR: ${(pe.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:We-ls-hn/2,y:Ve.top+$t-mt,width:ls,height:Math.max(mt,1),rx:2,fill:Ge[1],opacity:.85}),e.jsx("rect",{x:We+hn/2,y:Ve.top+$t-xs,width:ls,height:Math.max(xs,1),rx:2,fill:vs.positiveDeep,opacity:.85})]},pe.date)}),(()=>{const pe=Math.min(c.length,7);return Array.from({length:pe},(rt,We)=>{const mt=c.length===1?0:Math.round(We/(pe-1)*(c.length-1)),xs=Ve.left+Jt*mt+Jt/2;return e.jsx("text",{x:xs,y:Lt-8,textAnchor:"middle",fill:qe.textDim,fontSize:"10",fontFamily:"inherit",children:c[mt].date.slice(5)},`xl-${mt}`)})})()]})})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-5",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:_.startDate,onChange:c=>z(y=>({...y,startDate:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:_.endDate,onChange:c=>z(y=>({...y,endDate:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"Contains query…","aria-label":"Filter query (substring match)",title:"Case-insensitive substring match on the query column.",value:_.query,onChange:c=>z(y=>({...y,query:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"Contains page URL…","aria-label":"Filter page (substring match)",title:"Case-insensitive substring match on the page URL.",value:_.page,onChange:c=>z(y=>({...y,page:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"number",min:"1",placeholder:"Rows per page (20)","aria-label":"Rows per page",title:"Rows per page. Ignored while a filter or column sort is active — then up to 500 matches are loaded.",value:_.limit,onChange:c=>z(y=>({...y,limit:c.target.value}))})]}),e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. When a filter or column sort is active, up to ",gs.toLocaleString()," matching rows load so sorting covers the full set."]}),f.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(zt).map(c=>e.jsx("th",{className:"text-right","aria-sort":Fe?.key===c?Fe.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-zinc-200 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 rounded px-1 -mx-1",onClick:()=>dt(y=>y?.key===c?y.dir==="desc"?{key:c,dir:"asc"}:null:{key:c,dir:"desc"}),children:[Ki[c],Fe?.key===c?Fe.dir==="desc"?" ↓":" ↑":""]})},c))]})}),e.jsx("tbody",{children:W.map((c,y)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-400",children:c.date}),e.jsx("td",{className:"max-w-xs truncate text-zinc-200",children:c.query}),e.jsx("td",{className:"max-w-xs truncate text-zinc-400",children:c.page}),e.jsx("td",{className:"text-right tabular-nums text-zinc-300",children:c.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-400",children:[(Number.isFinite(c.ctr)?c.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.position.toFixed(1)})]},`${c.date}:${c.query}:${c.page}:${y}`))})]})}),Ne?e.jsx("div",{className:"mt-3 text-xs text-zinc-500",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",ee.toLocaleString()," matching row",ee===1?"":"s",ee>=gs?` (capped at ${gs.toLocaleString()} — narrow the filter to see more)`:""]})}):(H>0||he)&&(()=>{const c=parseInt(_.limit,10)||20,y=H+1,Y=H+f.length;return e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-zinc-500",children:[e.jsxs("span",{className:"tabular-nums",children:["Showing ",y.toLocaleString()," – ",Y.toLocaleString(),he?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:fe||H===0,onClick:()=>{const ie=Math.max(0,H-c);oe(ie),Dt(ie)},children:"Previous"}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:fe||!he,onClick:()=>{const ie=H+c;oe(ie),Dt(ie)},children:"Next"})]})]})})()]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No performance rows match the current filters yet."})]}),e.jsxs(K,{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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:p,onChange:c=>x(c.target.value),onKeyDown:c=>c.key==="Enter"&&void un()}),e.jsx(D,{type:"button",size:"sm",disabled:se||!ve?.propertyId||!p.trim(),onClick:X(un),children:se?"Inspecting…":"Inspect URL"})]}),A&&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-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:A.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:A.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:pn(A.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:Xe(A.crawlTime)})]})]})]}),e.jsxs(K,{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(D,{type:"button",variant:"outline",size:"sm",disabled:q,onClick:()=>{rs()},children:q?"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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:G,onChange:c=>Z(c.target.value)}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:q,onClick:()=>{rs()},children:"Apply filter"})]}),S.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:S.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-300",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.coverageState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:pn(c.isMobileFriendly??null)}),e.jsx("td",{className:"text-zinc-400",children:Xe(c.inspectedAt)})]},c.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No inspection history yet."})]}),e.jsxs(K,{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"})]})}),w.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:w.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.previousState??"Unknown"}),e.jsx("td",{className:"text-zinc-300",children:c.currentState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:Xe(c.transitionDate)})]},`${c.url}:${c.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No deindexed transitions recorded."})]})]}),ve&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-zinc-800/60 pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>Vt(c=>!c),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-zinc-500 transition-transform ${kt?"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-zinc-500",children:"Setup & Configuration"})]})}),kt&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(K,{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.jsx("h3",{children:"Pick the Search Console property"})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-zinc-500",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:E,disabled:ae||u.length===0,onChange:c=>v(c.target.value),children:u.length===0?e.jsx("option",{value:"",children:ae?"Loading properties…":"No properties available"}):u.map(c=>e.jsxs("option",{value:c.siteUrl,children:[c.siteUrl," · ",c.permissionLevel]},c.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:ae,onClick:()=>{cn(ve)},children:ae?"Refreshing…":"Refresh properties"}),e.jsx(D,{type:"button",size:"sm",disabled:!E||je,onClick:X(Ni),children:je?"Saving…":"Save property"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:"The selected property is used for future syncs and URL inspections for this project."})]})]}),e.jsxs(K,{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-zinc-500",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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",value:T,onChange:c=>U(c.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-zinc-800/60 bg-zinc-900/20 px-3 py-2 text-sm text-zinc-300",children:[e.jsx("input",{type:"checkbox",checked:P,onChange:c=>F(c.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(D,{type:"button",size:"sm",disabled:As.isPending||!ve.propertyId,onClick:X(wi),children:As.isPending?"Queueing…":"Queue sync"}),!ve.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property before queueing a sync."})]})]})]}),e.jsxs(K,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemap"}),e.jsx("h3",{children:"Sitemap configuration"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[ve.sitemapUrl&&e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Current sitemap URL"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200 break-all",children:ve.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:jt||!ve.propertyId,onClick:()=>{ji()},children:jt?"Loading…":"Browse sitemaps from GSC"}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:Yt.isPending||!ve.propertyId,onClick:X(dn),children:Yt.isPending?"Discovering…":"Auto-discover and queue inspection"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:"Browse lists available sitemaps without queueing a run. Auto-discover saves the primary sitemap and queues an inspection."}),_e&&_e.length>0&&e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:["Sitemaps (",_e.length,")"]}),_e.map(c=>{const y=c.contents?.[0];return e.jsxs("div",{className:"flex items-start justify-between gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-zinc-200 break-all",children:c.path}),c.lastSubmitted&&e.jsxs("p",{className:"text-zinc-500",children:["Submitted: ",c.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[y&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-zinc-300",children:[y.indexed," / ",y.submitted]}),e.jsx("p",{className:"text-zinc-500",children:"indexed"})]}),e.jsx("button",{type:"button",className:"text-xs text-zinc-400 hover:text-zinc-200 transition-colors",onClick:()=>Ye(c.path),children:"Use"})]})]},c.path)})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:ve.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:Ee,onChange:c=>Ye(c.target.value),onKeyDown:c=>c.key==="Enter"&&Ee.trim()&&void cs()}),e.jsx(D,{type:"button",size:"sm",disabled:tt||!Ee.trim(),onClick:X(cs),children:tt?"Saving…":ve.sitemapUrl?"Update":"Save"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"Sitemap URL for inspection (leave empty for saved default)",id:`gsc-sitemap-inspect-${t}`}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:Ds.isPending||!ve.propertyId,onClick:X(async()=>{const y=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||ve.sitemapUrl||void 0;me(null),at(null);try{await Ds.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:y}})}catch{}}),children:Ds.isPending?"Queueing…":"Inspect sitemap"})]}),!ve.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}function kc({projectName:t,projectId:s}){const n=bt(),[i,a]=r.useState(null),[l,o]=r.useState(!1),u=Pe(Js({client:V,path:{name:t}})),m=u.data?.find(z=>z.connectionType==="gbp"),f=!!m,j=i?{locationName:i}:void 0,d=Pe({...ca({client:V,path:{name:t}}),enabled:f}),I=Pe({...la({client:V,path:{name:t},query:j}),enabled:f}),S=Pe({...oa({client:V,path:{name:t},query:j}),enabled:f}),$=Pe({...da({client:V,path:{name:t},query:j}),enabled:f}),w=Pe({queryKey:["gbp-section-insights",t],queryFn:()=>xa(t),enabled:f});function L(){n.invalidateQueries({predicate:z=>{const H=z.queryKey[0];return typeof H?._id=="string"&&H._id.startsWith("getApiV1ProjectsByNameGbp")}})}const A=ss({...ua(),onSuccess:z=>{ma({id:z.runId,projectId:s,kind:js["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),ne({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),M=r.useSyncExternalStore(ha,fn,fn),E=Object.values(M.runs).some(z=>z.kind===js["gbp-sync"]&&z.projectId===s),v=A.isPending||E,p=ss({...pa(),onSuccess:()=>L()});if(r.useEffect(()=>{if(!i||!d.data)return;const z=d.data.locations.filter(H=>H.selected);(z.length<=1||!z.some(H=>H.locationName===i))&&a(null)},[i,d.data]),u.isLoading)return null;if(!m){const z=[{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-zinc-900/80 px-1 py-0.5 font-mono text-[11px] text-zinc-400",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-zinc-900/80 px-1 py-0.5 font-mono text-[11px] text-zinc-400",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(K,{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-zinc-500",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:z.map((H,oe)=>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-zinc-800 text-xs font-medium tabular-nums text-zinc-300","aria-hidden":"true",children:oe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:H.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-zinc-900/80 px-2 py-1 font-mono text-xs text-zinc-300",children:H.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-zinc-500",children:H.note})]})]},H.title))})]})})}const x=I.data,T=d.data?.locations??[],U=T.filter(z=>z.selected),P=S.data?.keywords??[],F=$.data?.places??[],k=T.length>0?T[0].accountName:m.domain,R=i?T.find(z=>z.locationName===i)?.displayName??null:null,_=(w.data??[]).filter(z=>!z.dismissed&&(z.type==="gbp-listing-discrepancy"||z.type==="gbp-lodging-gap")&&(!R||z.query===i||z.title.startsWith(R)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(K,{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(Ce,{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(ce,{tone:"positive",children:"Connected"}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:v,onClick:()=>A.mutate({client:V,path:{name:t},body:{}}),children:v?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-zinc-500",children:[k?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-zinc-400",children:k})," · "]}):null,d.data?`${d.data.totalSelected} of ${d.data.totalDiscovered} locations tracked`:"Loading locations…"]}),U.length>1&&e.jsxs("div",{className:"mb-5 flex flex-wrap gap-1.5",role:"tablist","aria-label":"Location",children:[e.jsx(An,{label:"All locations",active:i===null,onClick:()=>a(null)}),U.map(z=>e.jsx(An,{label:z.displayName,active:i===z.locationName,onClick:()=>a(z.locationName)},z.id))]}),U.length===0?e.jsxs("p",{className:"text-sm text-zinc-500",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-zinc-300",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[_.length>0&&e.jsx("div",{className:"mb-6 grid gap-2",children:_.map(z=>e.jsx("div",{className:"insight-card insight-card-negative rounded-r-lg border border-zinc-800/60 bg-zinc-900/30 p-3 pl-4",children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-zinc-200",children:[z.title,z.recommendation?.reason&&e.jsx(Ce,{text:z.recommendation.reason})]})},z.id))}),x&&e.jsx(Cc,{performance:x.performance,freshness:x.freshness,timeseries:x.timeseries}),F.length>0&&e.jsxs("div",{className:"mb-6",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Public listing · Google Maps"}),e.jsx("div",{className:"grid gap-2",children:F.map(z=>{const H=T.find(oe=>oe.locationName===z.locationName);return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:H?.displayName??z.locationName}),e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[z.amenities.length," amenit",z.amenities.length===1?"y":"ies"," advertised"]})]}),z.amenities.length>0?e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:z.amenities.map(oe=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 px-2 py-0.5 text-[11px] text-zinc-400",children:oe},oe))}):e.jsx("p",{className:"mt-1 text-sm text-zinc-500",children:"Public listing advertises no structured amenities."}),H?.mapsUri&&e.jsx("a",{href:H.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-block text-[11px] text-zinc-500 hover:text-zinc-300",children:"View on Google Maps →"})]},z.locationName)})})]}),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"}),S.data&&S.data.total>0&&e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[S.data.thresholdedPct,"% privacy-thresholded"]})]}),P.length===0?e.jsx("p",{className:"text-sm text-zinc-500",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"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:P.slice(0,25).map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-300",children:z.keyword}),e.jsx("td",{className:"text-right font-mono text-zinc-200",children:z.valueCount!==null?z.valueCount.toLocaleString():e.jsxs("span",{className:"text-zinc-500",title:"Privacy floor — Google withheld the exact count",children:["<",z.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-zinc-600",children:[z.periodStart,"–",z.periodEnd]})]},`${z.locationName}:${z.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-zinc-800/60 pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-zinc-400 hover:text-zinc-200",onClick:()=>o(z=>!z),"aria-expanded":l,children:[e.jsx("span",{"aria-hidden":"true",children:l?"▾":"▸"})," Manage locations (",T.length,")"]}),l&&e.jsx("div",{className:"mt-3",children:T.length===0?e.jsxs("p",{className:"text-sm text-zinc-500",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"}),e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:T.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-200",children:z.displayName}),e.jsx("td",{className:"text-zinc-500",children:z.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ce,{tone:z.selected?"positive":"neutral",children:z.selected?"Tracked":"Not tracked"})}),e.jsx("td",{className:"text-right",children:e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:p.isPending,onClick:()=>p.mutate({client:V,path:{name:t,locationName:z.locationName},body:{selected:!z.selected}}),children:z.selected?"Untrack":"Track"})})]},z.id))})]})})]})]})})}function An({label:t,active:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":s,onClick:n,className:`rounded-full border px-3 py-1 text-xs transition-colors ${s?"border-zinc-500 bg-zinc-800 text-zinc-100":"border-zinc-700/60 text-zinc-400 hover:border-zinc-600 hover:text-zinc-200"}`,children:t})}function Cc({performance:t,freshness:s,timeseries:n}){const i=t.totals,a=ga.filter($=>(i[$]??0)>0),l=fa.filter($=>(i[$]??0)>0),o=Object.keys(i).filter($=>(i[$]??0)>0&&ba($)==="other").sort(($,w)=>(i[w]??0)-(i[$]??0)),u=Object.keys(i).filter($=>(i[$]??0)===0).sort(),m=n.map($=>{const w={date:$.date};for(const[L,A]of Object.entries($.metrics))w[L]=A;return w}),f=n.find($=>$.pending)?.date,j=n.length>0?n[n.length-1].date:void 0,d=m.length>0,I=s.dataThroughDate?`Data through ${St(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,S=[...a,...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:"Conversions · daily"}),I&&e.jsx("span",{className:"text-[11px] text-zinc-500",children:I})]}),!d||a.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No conversion activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Dn,{data:m,metrics:a,kind:"line",firstPending:f,lastDate:j}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:S.map($=>e.jsxs("span",{className:"text-sm text-zinc-400",children:[ys($)," ",e.jsx("span",{className:"font-mono text-zinc-100",children:(i[$]??0).toLocaleString()})]},$))})]})]}),d&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Dn,{data:m,metrics:l,kind:"area",firstPending:f,lastDate:j})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Not active: ",u.map($=>ys($)).join(", ")]})]})}function Dn({data:t,metrics:s,kind:n,firstPending:i,lastDate:a}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Zs,{stroke:Xs,vertical:!1}),e.jsx(_t,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:ct},tickFormatter:Ft,minTickGap:24}),e.jsx(Ut,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Qt,{...ft,labelFormatter:St,formatter:(l,o)=>[typeof l=="number"?l.toLocaleString():String(l??0),ys(String(o??""))]}),e.jsx(ii,{wrapperStyle:{fontSize:11,color:qe.text},formatter:l=>ys(l)}),i&&a&&e.jsx(Gr,{x1:i,x2:a,fill:qe.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:qe.textDim,fontSize:10}}),s.map((l,o)=>n==="line"?e.jsx(en,{type:"monotone",dataKey:l,stroke:Ge[o%Ge.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(Pt,{type:"monotone",dataKey:l,stackId:"reach",stroke:Ge[o%Ge.length],fill:Ge[o%Ge.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function Es({children:t,label:s="More info",placement:n="top",className:i}){const a=r.useId(),[l,o]=r.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${i??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?a:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-zinc-500 hover:text-zinc-200 focus:text-zinc-200 focus:outline-none focus-visible:ring-1 focus-visible:ring-zinc-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(qr,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&e.jsx("span",{id:a,role:"tooltip",className:`absolute z-50 w-64 rounded border border-zinc-700 bg-zinc-900 px-3 py-2 text-xs font-normal leading-relaxed text-zinc-200 shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Nt=50,Ln={commoncrawl:"Common Crawl","bing-webmaster":"Bing Webmaster"},Ac={commoncrawl:"Common Crawl hyperlink graph · refreshes ~monthly when a release sync completes","bing-webmaster":"Bing Webmaster Tools · live inbound links from your connected account"};function wt(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function es(t){return t.toLocaleString()}function Dc(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Lc(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 i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function $c(t){const s=t.filter(n=>n.kind===js["backlink-extract"]&&!Wn(n.status));return s.length===0?null:s.reduce((n,i)=>n.createdAt>i.createdAt?n:i)}function Ic(t,s){const n=new Date(t??s).getTime(),i=Math.max(0,Math.floor((Date.now()-n)/1e3));if(i<60)return`${i}s`;const a=Math.floor(i/60),l=i%60;return l===0?`${a}m`:`${a}m ${l}s`}function Pc({projectName:t}){const[s,n]=r.useState(null),[i,a]=r.useState("commoncrawl"),[l,o]=r.useState(null),[u,m]=r.useState(null),[f,j]=r.useState([]),[d,I]=r.useState(null),[S,$]=r.useState(null),[w,L]=r.useState("commoncrawl"),[A,M]=r.useState(null),[E,v]=r.useState(Date.now()),[p,x]=r.useState(0),[T,U]=r.useState(!0),[P,F]=r.useState(!1),[k,R]=r.useState(!1),[_,z]=r.useState(null),H=r.useRef(null),oe=r.useRef(!1),he=r.useCallback(async()=>{U(!0),z(null);try{const[B,q,re,se,b,C]=await Promise.all([ja(t,{excludeCrawlers:!0}).catch(()=>null),ya().catch(()=>null),va(t,{excludeCrawlers:!0,source:i}).catch(()=>null),Na(t,{limit:Nt,offset:p,excludeCrawlers:!0,source:i}).catch(Te=>{if(Te instanceof Vs&&Te.code==="NOT_FOUND")return null;throw Te}),wa(t,{source:i}).catch(()=>[]),za(t).catch(()=>[])]);n(B),I(q),o(re),m(se),j(b);const Ae=$c(C);$(Ae),H.current=Ae?.id??null}catch(B){z(B instanceof Error?B.message:"Failed to load backlinks")}finally{U(!1)}},[t,p,i]);r.useEffect(()=>{he()},[he]),r.useEffect(()=>{if(!s||oe.current)return;const B=s.sources.find(se=>se.hasData),q=s.sources.find(se=>se.connected),re=B?.source??q?.source;re&&re!==i&&a(re)},[s,i]);function be(B){oe.current=!0,x(0),a(B)}r.useEffect(()=>{if(!S)return;const B=S.id;let q=!1;const re=async()=>{try{const b=await Hn(B);if(q)return;Wn(b.status)?($(null),M(b),await he()):$(C=>C?.id===b.id?{...C,...b}:C)}catch{}},se=window.setInterval(()=>{re()},3e3);return()=>{q=!0,window.clearInterval(se)}},[S,he]),r.useEffect(()=>{if(!S)return;const B=window.setInterval(()=>v(Date.now()),1e3);return()=>window.clearInterval(B)},[S]),r.useEffect(()=>{if(!A||A.status==="failed")return;const B=window.setTimeout(()=>M(null),1e4);return()=>window.clearTimeout(B)},[A]);async function ee(){F(!0),z(null);try{const B=await Aa(t);L("commoncrawl"),$(B),H.current=B.id}catch(B){B instanceof Vs&&B.code==="MISSING_DEPENDENCY"?z("DuckDB is not installed. Visit the Backlinks admin page to install it."):z(B instanceof Error?B.message:"Failed to trigger extract")}finally{F(!1)}}async function ge(){R(!0),z(null);try{const B=await Ca(t);L("bing-webmaster"),$(B),H.current=B.id}catch(B){z(B instanceof Error?B.message:"Failed to trigger Bing sync")}finally{R(!1)}}const Ne=r.useMemo(()=>f.slice().sort((B,q)=>B.queriedAt.localeCompare(q.queriedAt)).map(B=>({date:B.queriedAt,linkingDomains:B.totalLinkingDomains})),[f]),g=u?.rows??[],G=u?.total??0,Z=l?.excludedLinkingDomains??0,le=G>Nt,ue=Math.floor(p/Nt)+1,Re=Math.max(1,Math.ceil(G/Nt));return r.useEffect(()=>{p>0&&p>=G&&x(0)},[p,G]),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"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1 max-w-2xl",children:["Domains linking to "," ",e.jsx("span",{className:"text-zinc-300",children:t}),", from whichever source you have set up — the"," ",e.jsx("span",{className:"text-zinc-300",children:"Common Crawl"})," hyperlink graph (~monthly) and"," ",e.jsx("span",{className:"text-zinc-300",children:"Bing Webmaster"})," inbound links (live)."]})]})}),_&&e.jsx(K,{className:"surface-card p-4 mb-4 border-rose-800/60",children:e.jsx("p",{className:"text-sm text-rose-300",children:_})}),S&&e.jsx(K,{className:"surface-card p-4 mb-4 border-sky-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Sa,{className:"h-5 w-5 text-sky-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-zinc-100",children:w==="bing-webmaster"?"Bing sync running":"Extract running"}),e.jsx(ce,{tone:"neutral",children:S.status}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:[Ic(S.startedAt??null,S.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",E]})]}),w==="bing-webmaster"?e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:["Pulling inbound links live from Bing Webmaster for"," ",e.jsx("span",{className:"text-zinc-300",children:t}),". Time depends on how many pages link to your site."]}):e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:["Re-querying the cached Common Crawl release for"," ",e.jsx("span",{className:"text-zinc-300",children:t}),". No re-download — the ~16 GB dump already lives at"," ",e.jsx("code",{className:"text-zinc-400",children:"~/.canonry/cache/commoncrawl/"}),". Typically takes ~5 minutes."]})]})]})}),A&&!S&&e.jsx(K,{className:`surface-card p-4 mb-4 ${A.status==="failed"?"border-rose-800/60":"border-emerald-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[A.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-rose-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(ai,{className:"h-5 w-5 text-emerald-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${A.status==="failed"?"text-rose-300":"text-emerald-300"}`,children:w==="bing-webmaster"?A.status==="failed"?"Bing sync failed":"Bing sync complete":A.status==="failed"?"Extract failed":"Extract complete"}),A.error?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:ka(A.error)}):A.status!=="failed"?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:w==="bing-webmaster"?"Inbound links refreshed live from Bing Webmaster.":"Backlinks refreshed from the cached release."}):null]})]})}),we()]});function we(){return T||!s?e.jsx(K,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading backlinks…"})}):!s.anyConnected&&!s.anyData?te():e.jsxs(e.Fragment,{children:[ae(s),i==="bing-webmaster"?je():ze()]})}function ae(B){return e.jsx("div",{className:"flex items-center gap-2 mb-4 flex-wrap",role:"tablist","aria-label":"Backlink source",children:B.sources.map(q=>{const re=q.source===i,se=q.hasData?"bg-emerald-500":q.connected?"bg-amber-500":"bg-zinc-600";return e.jsxs("button",{type:"button",role:"tab","aria-selected":re,onClick:()=>be(q.source),className:`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-zinc-500 ${re?"border-zinc-500 bg-zinc-800 text-zinc-100":"border-zinc-800 bg-zinc-900/40 text-zinc-400 hover:text-zinc-200"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${se}`,"aria-hidden":!0}),Ln[q.source],q.hasData&&e.jsx("span",{className:"text-zinc-500 tabular-nums",children:es(q.totalLinkingDomains)})]},q.source)})})}function te(){return e.jsx(K,{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-zinc-900 text-zinc-400",children:e.jsx($s,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No backlink source set up yet"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1 max-w-2xl",children:["Connect at least one source to see which domains link to"," ",e.jsx("code",{className:"text-zinc-300",children:t}),":"]}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-zinc-400",children:[e.jsxs("li",{children:[e.jsx("span",{className:"text-zinc-200",children:"Common Crawl"})," — free public hyperlink graph, refreshes ~monthly. Enable backlinks and run a workspace release sync."]}),e.jsxs("li",{children:[e.jsx("span",{className:"text-zinc-200",children:"Bing Webmaster"})," — live inbound links from your verified site. Connect a Bing Webmaster account, then sync."]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:wt("/backlinks"),children:"Set up Common Crawl"})})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-500",children:["Connect Bing with"," ",e.jsxs("code",{className:"text-zinc-400",children:["canonry bing connect ",t," --api-key <key>"]}),"."]})]})]})})}function je(){const B=s?.sources.find(b=>b.source==="bing-webmaster"),q=B?.connected??!1,re=B?.hasData??!1;return l!==null&&l.totalLinkingDomains>0?fe(e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:k||S!==null,onClick:X(ge),children:[e.jsx(ts,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),S?"Sync running…":k?"Queuing…":"Re-sync Bing"]})):e.jsx(K,{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-zinc-900 text-zinc-400",children:e.jsx($s,{className:"h-5 w-5","aria-hidden":!0})}),e.jsx("div",{className:"flex-1",children:q&&re?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No non-crawler referring domains"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["Bing Webmaster synced for ",e.jsx("code",{className:"text-zinc-300",children:t}),", but every inbound link in the latest window is a crawler/proxy host (hidden by default). Re-sync to check for new links."]}),e.jsx("div",{className:"mt-4",children:e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:k||S!==null,onClick:X(ge),children:[e.jsx(ts,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),S?"Sync running…":k?"Queuing…":"Re-sync Bing inbound links"]})})]}):q?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No Bing inbound links yet"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["Bing Webmaster is connected for ",e.jsx("code",{className:"text-zinc-300",children:t})," but no inbound links have been synced yet. Run a sync to pull them live from your account."]}),e.jsx("div",{className:"mt-4",children:e.jsxs(D,{type:"button",size:"sm",disabled:k||S!==null,onClick:X(ge),children:[e.jsx(Et,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),S?"Sync running…":k?"Queuing…":"Sync Bing inbound links"]})})]}):e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Bing Webmaster not connected"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["Connect a Bing Webmaster account for ",e.jsx("code",{className:"text-zinc-300",children:t})," to pull live inbound links, then sync."]}),e.jsxs("pre",{className:"mt-3 rounded bg-zinc-900 border border-zinc-800 px-3 py-2 text-xs text-zinc-300 overflow-x-auto",children:["canonry bing connect ",t," --api-key <key>"]})]})})]})})}function ze(){const B=l!==null&&l.totalLinkingDomains>0,q=A?.status==="failed",re=l!==null&&l.totalLinkingDomains===0&&!q,se=d?.status==="ready",b=d?.status==="failed",C=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return B?fe(e.jsxs(e.Fragment,{children:[e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:P||S!==null,onClick:X(ee),children:[e.jsx(ts,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),S?"Extract running…":P?"Queuing…":"Re-run extract"]}),e.jsxs(Es,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the ",e.jsx("span",{className:"text-zinc-200",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-zinc-300",children:"~/.canonry/cache/commoncrawl/"})," for ",e.jsx("span",{className:"text-zinc-200",children:t}),". Replaces existing backlink rows for this project under the current release."]}),e.jsxs("span",{className:"mt-2 block text-zinc-400",children:[e.jsx("span",{className:"text-zinc-200",children:"No re-download"})," of the ~16 GB dump. Typically ",e.jsx("span",{className:"text-zinc-200",children:"~5 min"}),"."]})]}),e.jsx(D,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:wt("/backlinks"),children:"Open admin"})})]})):e.jsx(K,{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-zinc-900 text-zinc-400",children:e.jsx($s,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-zinc-500 mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),e.jsx("div",{className:"mt-4",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:wt("/backlinks"),children:"Set up backlinks"})})})]}),C&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["A workspace release sync is running (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),e.jsx("div",{className:"mt-4",children:e.jsx(D,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:wt("/backlinks"),children:"View sync status"})})})]}),b&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-zinc-500 mt-1",children:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),e.jsx("div",{className:"mt-4",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:wt("/backlinks"),children:"Go to Backlinks admin"})})})]}),se&&!C&&!re&&!q&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["Release ",e.jsx("code",{className:"text-zinc-300",children:d.release})," is ready but no backlinks have been extracted for"," ",e.jsx("code",{className:"text-zinc-300",children:t}),". Run an extract to populate data using the cached release."]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(D,{type:"button",size:"sm",disabled:P||S!==null,onClick:X(ee),children:[e.jsx(Et,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),S?"Extract running…":P?"Queuing…":"Run extract"]}),e.jsxs(Es,{label:"What does Run extract do?",children:[e.jsxs("span",{className:"block",children:["Runs a DuckDB query against the ",e.jsx("span",{className:"text-zinc-200",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-zinc-300",children:"~/.canonry/cache/commoncrawl/"})," to find referring domains for ",e.jsx("span",{className:"text-zinc-200",children:t}),"."]}),e.jsxs("span",{className:"mt-2 block text-zinc-400",children:["No re-download. Typically takes ",e.jsx("span",{className:"text-zinc-200",children:"~5 min"}),"."]})]})]})]}),q&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Last extract failed"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["See the error above for details. If the cache files for release"," ",e.jsx("code",{className:"text-zinc-300",children:d?.release})," are missing, re-sync the release from the Backlinks admin to restore the ~16 GB dump, then re-run the extract."]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:wt("/backlinks"),children:"Go to Backlinks admin"})})})]}),re&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["The last extract against release ",e.jsx("code",{className:"text-zinc-300",children:l.release})," found"," ",e.jsx("span",{className:"text-zinc-300",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-zinc-300",children:l.targetDomain}),". This can happen when:"]}),e.jsxs("ul",{className:"mt-2 space-y-1 text-xs text-zinc-500 list-disc list-inside",children:[e.jsx("li",{children:"the domain is newer than the release’s crawl window"}),e.jsx("li",{children:"the Common Crawl snapshot didn’t capture pages that link to it"}),e.jsx("li",{children:"the extract ran against a cache that was missing or incomplete"})]}),e.jsx("p",{className:"text-sm text-zinc-500 mt-3",children:"Try syncing a newer release — each Common Crawl dump is a different snapshot of the web graph."}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:wt("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:P||S!==null,onClick:X(ee),children:[e.jsx(Et,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),S?"Extract running…":P?"Queuing…":"Re-run extract"]}),e.jsxs(Es,{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-zinc-200",children:l.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-zinc-400",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 fe(B){if(!l)return null;const q=i==="bing-webmaster",re=q?"Inbound links":"Linking hosts",se=q?"inbound links":"linking hosts",b=q?"window":"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-zinc-50",children:es(l.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",l.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",se]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-zinc-50",children:es(l.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",se," 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-zinc-50",children:Dc(l.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",se," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-zinc-600 mt-2",children:[e.jsx("span",{className:"text-zinc-400",children:Ln[i]})," · ",b," ",e.jsx("code",{className:"text-zinc-400",children:l.release})," · queried ",Lc(l.queriedAt),Z>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-zinc-500",children:[Z," crawler/proxy domain",Z===1?"":"s"," hidden"]})]})]}),e.jsx("p",{className:"text-[11px] text-zinc-600 mt-0.5",children:Ac[i]}),Ne.length>=2&&e.jsxs(K,{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(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:Ne,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:Ge[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:Ge[0],stopOpacity:0})]})}),e.jsx(_t,{dataKey:"date",tick:He,stroke:ct,tickFormatter:Ft}),e.jsx(Ut,{tick:He,stroke:ct,allowDecimals:!1}),e.jsx(Qt,{contentStyle:ft.contentStyle,labelStyle:ft.labelStyle,itemStyle:ft.itemStyle,labelFormatter:St}),e.jsx(Pt,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:Ge[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Top referring domains"}),le&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Page ",ue," of ",Re," · ",es(G)," total"]})]}),e.jsx(K,{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-zinc-800 text-left text-xs uppercase tracking-wide text-zinc-600",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:re})]})}),e.jsxs("tbody",{children:[g.map(C=>e.jsxs("tr",{className:"border-b border-zinc-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-zinc-200",children:C.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-zinc-400 tabular-nums",children:es(C.numHosts)})]},C.linkingDomain)),g.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-zinc-500",colSpan:2,children:Z>0&&G===0?`Every referring domain in this ${b} was a crawler/proxy host (${Z} hidden).`:`No referring domains in this ${b}.`})})]})]})}),le&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:p===0,onClick:()=>x(C=>Math.max(0,C-Nt)),children:"Previous"}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:p+Nt>=G,onClick:()=>x(C=>C+Nt),children:"Next"})]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:B})]})}}function Rc({projectName:t}){const s=Pe({...Da({client:V,path:{name:t}}),staleTime:Yn}),n=s.data??null,i=s.error;if(s.isLoading&&!n)return null;if(i)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-rose-400",children:i instanceof Error?i.message:String(i)})]});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-zinc-500",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:a,providersMentioning:l,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 ",a," of ",o," engines",e.jsx(Ce,{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-zinc-300 flex items-center gap-2",children:["Mentioned in ",l," of ",o," engine answers",e.jsx(Ce,{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(Tc,{data:n}),e.jsx(Ec,{data:n}),n.competitorGaps.length>0&&e.jsx(Fc,{data:n})]})}function Tc({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:i,queriesMentionedOnly:a,queriesInvisible:l}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(fs,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(fs,{label:"Cited only",value:`${i} / ${s}`,helper:"In sources, not named in answer",tone:i>0?"positive-dim":"neutral"}),e.jsx(fs,{label:"Mentioned only",value:`${a} / ${s}`,helper:"Named in answer, no source link",tone:a>0?"caution":"neutral"}),e.jsx(fs,{label:"Invisible",value:`${l} / ${s}`,helper:"No engine cites or mentions",tone:l>0?"negative":"neutral"})]})}function fs({label:t,value:s,helper:n,tone:i}){const a=i==="positive"?"text-emerald-300":i==="positive-dim"?"text-emerald-400/70":i==="caution"?"text-amber-300":i==="negative"?"text-rose-300":"text-zinc-100";return e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:n})]})}function Ec({data:t}){const s=r.useMemo(()=>{const n=new Set;for(const i of t.byQuery)for(const a of i.providers)n.add(a.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(Mc,{}),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(Ot,{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-zinc-100",children:n.query}),s.map(i=>{const a=n.providers.find(l=>l.provider===i);return e.jsx("td",{className:"text-center",children:a==null?e.jsx(Qr,{className:"inline h-3.5 w-3.5 text-zinc-700","aria-label":"no data"}):e.jsx(Bc,{provider:a})},i)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-emerald-300":n.citedCount>0?"text-emerald-400/70":"text-zinc-500",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-sky-300":n.mentionedCount>0?"text-sky-400/70":"text-zinc-500",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function Mc(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-zinc-500",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{active:!1,tone:"cited"}),e.jsx(Rt,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Bc({provider:t}){const s=Oc(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Rt,{active:t.cited,tone:"cited"}),e.jsx(Rt,{active:t.mentioned,tone:"mentioned"})]})}function Oc(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 Rt({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-zinc-700/80 bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-emerald-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-sky-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Fc({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-zinc-200 mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Ce,{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-zinc-500",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-zinc-100",children:s.query}),e.jsx("td",{children:e.jsx(Ot,{provider:s.provider})}),e.jsx("td",{className:"text-zinc-300",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ks="__cited__",Cs="__mentioned__";function $n(t){return Math.round(t*1e3)/10}function Gc(t,s,n){const i=t.buckets.length>0,a=t.buckets.length===1;if(n==="overall"){const m=s==="cited"?ks:Cs,f=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[m]:$n(d[f])})),series:[m],hasData:i,singleBucket:a}}const l=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(m=>Object.keys(m.byProvider??{})))].sort();return{rows:t.buckets.map(m=>{const f={date:m.startDate};for(const j of o){const d=m.byProvider?.[j];f[j]=d?$n(d[l]):null}return f}),series:o,hasData:i,singleBucket:a}}function qc(t,s){for(let n=t.length-1;n>=0;n--){const i=t[n][s];if(typeof i=="number"&&Number.isFinite(i))return i}return null}function In(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Pn(t){return t>0?`+${t}`:`${t}`}function _c(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Pn(n.delta)} on ${In(n.date)}`).join(", ")}`;const s=[...t].sort((n,i)=>i.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Pn(s.delta)} on ${In(s.date)})`}const Uc=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Qc=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Kc=[{value:"mentioned",label:"Mentioned"},{value:"cited",label:"Cited"}],Vc="#18181b",Wc={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Hc(t){return Wc[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Ms(t){return Math.round(t*10)/10}function Yc(t){return t===ks||t===Cs}function Rn(t){return t===ks?"Cited":t===Cs?"Mentioned":Hc(t)}function Bs(t,s){return t===ks?vs.positive:t===Cs?Ge[1]:Mr(t,s)}function Os({options:t,value:s,onChange:n,ariaLabel:i,className:a}){return e.jsx("div",{role:"group","aria-label":i,className:`segmented ${a??""}`,children:t.map(l=>{const o=s===l.value;return e.jsx("button",{type:"button","aria-pressed":o,className:`segmented-option ${o?"segmented-option-active":""}`,onClick:()=>n(l.value),children:l.label},l.value)})})}function Jc({projectName:t}){const[s,n]=r.useState("all"),[i,a]=r.useState("mentioned"),[l,o]=r.useState("byProvider"),u=Pe({queryKey:["analytics-metrics",t,s],queryFn:()=>La(t,s),staleTime:Yn}),m=u.data??null,f=u.error,j=r.useMemo(()=>m?Gc(m,i,l):null,[m,i,l]),d=l==="byProvider",I=i==="cited"?"citationRate":"mentionRate",S=i==="cited"?"Cited":"Mentioned",$=i==="cited"?vs.positive:Ge[1],w=d?qe.textDim:$,L=m?.buckets??[],A=L.length>0?Ms(L[L.length-1][I]*100):null,M=L.length>0?Ms(L[0][I]*100):null,E=A!==null&&M!==null&&L.length>1?Ms(A-M):null,v=e.jsxs(e.Fragment,{children:[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:["Citations & mentions over time",e.jsx(Ce,{text:"How often AI engines cited your domain as a source (Cited) and named your brand in the answer text (Mentioned), across all tracked queries, over time. Each point is a sweep bucket; rates are the share of (query × provider) snapshots in that bucket."})]})]}),A!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:w},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:S}),d&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[A,"%"]}),E!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${E>0?"text-emerald-400":E<0?"text-rose-400":"text-zinc-500"}`,children:[E>0?"+":"",E.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Os,{options:Kc,value:i,onChange:a,ariaLabel:"Metric"}),e.jsx(Os,{options:Qc,value:l,onChange:o,ariaLabel:"Series"}),e.jsx(Os,{options:Uc,value:s,onChange:n,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let p;if(f)p=e.jsx("p",{className:"text-sm text-rose-400",children:f instanceof Error?f.message:String(f)});else if(u.isLoading&&!m)p=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-zinc-900/40","aria-hidden":"true"});else if(!m||!j)p=null;else{const{rows:x,series:T,hasData:U,singleBucket:P}=j,F=_c(m.queryChanges);if(!U)p=e.jsx("p",{className:"text-sm text-zinc-400",children:"Run a sweep to start tracking citations and mentions over time."});else if(l==="byProvider"&&T.length===0)p=e.jsxs("p",{className:"text-sm text-zinc-400",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-zinc-200",children:"All engines"})," to see the trend."]});else{const k=`${S} rate across ${x.length} ${x.length===1?"sweep":"sweeps"}. Latest ${A}%${E!==null?`, ${E>=0?"up":"down"} ${Math.abs(E).toFixed(1)} points over the period`:""}.`;p=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:k}),l==="byProvider"&&T.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:T.map((R,_)=>{const z=qc(x,R);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Bs(R,_)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:Rn(R)}),z!==null&&e.jsxs("span",{className:"trend-legend-value",children:[z,"%"]})]},R)})}),e.jsx("div",{className:"visibility-trend-chart",children:e.jsx(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:x,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Zs,{stroke:Xs,vertical:!1}),e.jsx(_t,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:ct},tickFormatter:Ft,minTickGap:24}),e.jsx(Ut,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:R=>`${R}%`,tick:He,tickLine:!1,axisLine:!1,width:40}),e.jsx(Qt,{...ft,cursor:{stroke:ct,strokeWidth:1},labelFormatter:St,formatter:(R,_)=>[R==null?"no data":`${R}%`,Rn(String(_))]}),T.map((R,_)=>e.jsx(en,{type:"monotone",dataKey:R,name:R,stroke:Bs(R,_),strokeWidth:Yc(R)?2.5:2,dot:{r:2.5,fill:Bs(R,_),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Vc},connectNulls:!0,isAnimationActive:!1},R))]})})}),P&&e.jsx("p",{className:"visibility-trend-note",children:"Only one sweep so far. The trend line fills in after the next run."}),F&&e.jsx("p",{className:"visibility-trend-note",children:F})]})}}return e.jsxs("section",{className:"visibility-trend",children:[v,p]})}const Ys=new Set(["queued","seeding","probing"]);function Xc({projectName:t}){const s=bt(),[n,i]=r.useState(null),[a,l]=r.useState(""),[o,u]=r.useState("100"),m=Pe({...$a({client:V,path:{name:t},query:{limit:"10"}}),refetchInterval:v=>v.state.data?.some(x=>Ys.has(x.status))?3e3:!1}),f=m.data??[];r.useEffect(()=>{!n&&f[0]&&i(f[0].id)},[n,f]);const j=f.find(v=>v.id===n)??null,d=Pe({...Ia({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:j&&Ys.has(j.status)?3e3:!1}),I=d.data??null,S=Pe({...Pa({client:V,path:{name:t,id:n??""}}),enabled:!!(n&&j?.status==="completed")}),$=ss({mutationFn:()=>{const v={},p=a.trim();p&&(v.icpDescription=p);const x=Number.parseInt(o,10);return Number.isFinite(x)&&x>0&&(v.maxProbes=x),Ra(t,v)},onSuccess:async v=>{i(v.sessionId),l(""),await En(s,t,v.sessionId),ne({title:"Discovery started",detail:`Run ${Fs(v.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${v.sessionId}`,dedupeMode:"replace"})},onError:v=>{ne({title:"Discovery failed to start",detail:v instanceof Error?v.message:"Could not start discovery.",tone:"negative"})}}),w=ss({mutationFn:v=>{if(!n)throw new Error("Select a completed discovery session first.");return Ta(t,n,v)},onSuccess:async v=>{await En(s,t,v.sessionId),s.invalidateQueries({queryKey:Jn({client:V})}),s.invalidateQueries({predicate:p=>Array.isArray(p.queryKey)&&p.queryKey[0]==="projects"&&p.queryKey.length>1}),ne({title:"Queries added",detail:sl(v),tone:"positive",dedupeKey:`discovery:promote:${v.sessionId}`,dedupeMode:"replace"})},onError:v=>{ne({title:"Could not add queries",detail:v instanceof Error?v.message:"Could not add queries from this run.",tone:"negative"})}}),L=I??j,A=S.data??null,M=(A?.queriesByBucket.cited.length??0)+(A?.queriesByBucket.aspirational.length??0),E=r.useMemo(()=>(I?.probes??[]).slice(0,30),[I?.probes]);return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Discovery"}),e.jsx("h2",{children:"Find new queries to track"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-500",children:"Describe your ideal customer and Canonry generates the questions they would ask an AI engine, checks which ones already cite your site, then lets you add the promising ones to your tracked queries."})]}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{m.refetch()},children:[e.jsx(Ns,{size:14}),"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(K,{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(ce,{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-xs text-zinc-500",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-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:a,onChange:v=>l(v.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-zinc-500",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",inputMode:"numeric",value:o,onChange:v=>u(v.target.value)}),e.jsx("span",{className:"mt-1 block text-[11px] text-zinc-600",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),e.jsxs(D,{type:"button",size:"sm",disabled:$.isPending,onClick:()=>$.mutate(),children:[e.jsx(Et,{size:14}),$.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(K,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),m.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),f.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:f.map(v=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===v.id?"border-zinc-600 bg-zinc-900/70":"border-zinc-800/60 bg-zinc-950/40 hover:border-zinc-700 hover:bg-zinc-900/40"}`,onClick:()=>i(v.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:Fs(v.id)}),e.jsx(ce,{tone:Tn(v.status),children:v.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-[11px] text-zinc-500",children:[e.jsxs("span",{children:["Cited ",v.citedCount??0]}),e.jsxs("span",{children:["Opportunity ",v.aspirationalCount??0]}),e.jsxs("span",{children:["Low value ",v.wastedCount??0]})]})]},v.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(K,{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:L?Fs(L.id):"No run selected"})]}),L&&e.jsx(ce,{tone:Tn(L.status),children:L.status})]}),L?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ht,{label:"Questions tested",value:L.probeCount??0}),e.jsx(ht,{label:"Already cited",value:L.citedCount??0,tone:"positive"}),e.jsx(ht,{label:"Opportunities",value:L.aspirationalCount??0,tone:"caution"}),e.jsx(ht,{label:"Low value",value:L.wastedCount??0,tone:"negative"})]}),L.error&&e.jsx("div",{className:"rounded-md border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:L.error}),L.warning&&e.jsx("div",{className:"rounded-md border border-amber-800/40 bg-amber-950/20 px-3 py-2 text-sm text-amber-300",children:L.warning}),L.icpDescription&&e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-300",children:L.icpDescription})]}),L.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:L.competitorMap.slice(0,8).map(v=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[v.domain," ",e.jsx("span",{className:"text-zinc-500",children:v.hits})]},v.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),L?.status==="completed"&&e.jsxs(K,{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:"Add queries to your project"})]}),e.jsxs(D,{type:"button",size:"sm",disabled:w.isPending||M===0,onClick:()=>w.mutate(void 0),children:[e.jsx(ai,{size:14}),w.isPending?"Adding…":"Add recommended queries"]})]}),S.isLoading?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading recommendations…"}):A?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ht,{label:"Queries to add",value:M,tone:"positive"}),e.jsx(ht,{label:"Already cited",value:A.queriesByBucket.cited.length,tone:"positive"}),e.jsx(ht,{label:"Opportunities",value:A.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(ht,{label:"Low value (skipped)",value:A.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-xs leading-5 text-zinc-500",children:"Adding queries starts tracking the “already cited” and “opportunity” questions, plus any competitor sites that kept showing up. “Low value” questions are listed below for reference only and are not added."}),A.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:A.suggestedCompetitors.map(v=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[v.domain," ",e.jsx("span",{className:"text-zinc-500",children:v.hits})]},v.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"No recommendations available for this run."})]}),e.jsxs(K,{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"})]}),d.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),E.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"})]})}),e.jsx("tbody",{children:E.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-zinc-100",children:v.query}),e.jsx("td",{children:e.jsx(ce,{tone:Zc(v.bucket),children:tl(v.bucket)})}),e.jsx("td",{className:"text-zinc-400",children:v.citedDomains.length>0?v.citedDomains.slice(0,3).join(", "):"-"})]},v.id))})]})})]})]})]})]})}function ht({label:t,value:s,tone:n="neutral"}){const i=n==="positive"?"text-emerald-300":n==="caution"?"text-amber-300":n==="negative"?"text-rose-300":"text-zinc-100";return e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s})]})}function Tn(t){return t==="completed"?"positive":t==="failed"?"negative":Ys.has(t)?"caution":"neutral"}function Zc(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const el={cited:"Already cited",aspirational:"Opportunity","wasted-surface":"Low value"};function tl(t){return t?el[t]:"Not classified"}function Fs(t){return t.length>8?t.slice(0,8):t}function sl(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,i=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${i>0?`; ${i} already tracked`:""}.`}async function En(t,s,n){await Promise.all([t.invalidateQueries({predicate:i=>{const a=i.queryKey[0];return typeof a?._id=="string"&&a._id.startsWith("getApiV1ProjectsByNameDiscover")}}),t.invalidateQueries({queryKey:Xn({client:V})})])}const Mn=100,Gs=12;function qs(t){return t>=70?"positive":t>=40?"caution":"negative"}function _s(t){return t>=70?"text-emerald-400":t>=40?"text-amber-400":"text-rose-400"}function nl(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function bs(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function il({projectName:t}){const s=bt(),[n,i]=r.useState(!1),[a,l]=r.useState(null),o=Pe(Ea({client:V,path:{name:t}})),u=Pe(Ma({client:V,path:{name:t},query:{limit:30}})),m=Pe(Ba({client:V,path:{name:t},query:{limit:Mn,sort:"score-asc"}})),f=ss({mutationFn:()=>Oa(t),onSuccess:()=>{ne({title:"Technical audit started",detail:"The audit re-reads your sitemap in the background. Refresh in a minute to see the score.",tone:"positive"}),s.invalidateQueries({queryKey:Xn({client:V})})},onError:x=>{ne({title:"Could not start technical audit",detail:x instanceof Error?x.message:"Failed to start technical audit.",tone:"negative"})}}),j=()=>{s.invalidateQueries({queryKey:Ga({client:V,path:{name:t}})}),s.invalidateQueries({queryKey:qa({client:V,path:{name:t},query:{limit:30}})}),s.invalidateQueries({queryKey:_a({client:V,path:{name:t},query:{limit:Mn,sort:"score-asc"}})})},d=o.data;if(o.isLoading)return e.jsx("p",{className:"supporting-copy mt-6",children:"Loading technical audit…"});if(!d||!d.hasData)return e.jsxs(K,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(Vr,{className:"mx-auto mb-3 h-8 w-8 text-zinc-500","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:"No technical audit yet"}),e.jsx("p",{className:"supporting-copy mx-auto mt-2 max-w-md",children:"A technical AEO audit crawls your sitemap and scores every page for structured data, AI-readable content, crawler access, freshness, and more, then rolls it up into one site score."}),e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(D,{type:"button",onClick:()=>f.mutate(),disabled:f.isPending,children:[e.jsx(Et,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),f.isPending?"Starting…":"Run first audit"]})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-600",children:["Or from the CLI: ",e.jsxs("code",{className:"text-zinc-400",children:["canonry technical-aeo run ",t," --wait"]})]})]});const I=d.deltaScore==null?null:`${d.deltaScore>=0?"+":""}${d.deltaScore} vs previous`,S=d.trend==="up"?"positive":d.trend==="down"?"negative":"neutral",$=u.data?.points.map(x=>({date:x.auditedAt,score:x.aggregateScore}))??[],w=m.data?.pages??[],L=w.filter(x=>x.status==="success"),A=d.pagesErrored>0,M=n&&A,E=M?w.filter(x=>x.status==="error"):w,v=d.pagesAudited>w.length;function p(x){const T=[];for(const U of L){const P=U.factors.find(F=>F.id===x);P&&P.score<70&&T.push({url:U.url,score:P.score})}return T.sort((U,P)=>U.score-P.score)}return e.jsxs("div",{className:"mt-6",children:[e.jsxs("section",{className:"surface-card flex flex-wrap items-start justify-between gap-6 rounded-lg border border-zinc-800/60 bg-zinc-900/30 p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${_s(d.aggregateScore)}`,children:d.aggregateScore}),e.jsx("span",{className:"text-lg text-zinc-500",children:"/ 100"}),e.jsx(ce,{tone:qs(d.aggregateScore),children:bs(d.aggregateScore)}),I?e.jsx(ce,{tone:S,children:I}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[d.pagesDiscovered," URL",d.pagesDiscovered===1?"":"s"," in sitemap · ",d.pagesAudited," audited · ",d.pagesSkipped," skipped · ",d.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-zinc-500",children:[e.jsx("span",{className:"text-zinc-600",children:"Sitemap:"}),e.jsx("a",{href:d.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-zinc-400 underline decoration-zinc-700 underline-offset-2 hover:text-zinc-200",children:d.sitemapUrl}),e.jsx(Ce,{text:"Every audit re-reads this sitemap, so pages you add or remove are picked up on the next run. Discovered/audited counts and the score reflect the sitemap at the time of the latest run. Override it with `canonry technical-aeo run <project> --sitemap-url <url>`."})]}),d.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-zinc-600",children:["Audited ",new Date(d.auditedAt).toLocaleString()]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(D,{type:"button",variant:"outline",size:"sm",onClick:j,children:[e.jsx(Ns,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),"Refresh"]}),e.jsxs(D,{type:"button",size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,children:[e.jsx(Et,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),f.isPending?"Starting…":"Re-run audit"]})]})]}),$.length>=2?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h2",{children:"Site score over time"})]}),e.jsx("div",{className:"mt-3 h-56",children:e.jsx(Gt,{width:"100%",height:"100%",children:e.jsxs(qt,{data:$,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Zs,{stroke:Xs,vertical:!1}),e.jsx(_t,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:ct},tickFormatter:Ft,minTickGap:24}),e.jsx(Ut,{domain:[0,100],ticks:[0,25,50,75,100],tick:He,tickLine:!1,axisLine:!1,width:32}),e.jsx(Qt,{...ft,cursor:{stroke:ct,strokeWidth:1},labelFormatter:St,formatter:x=>[`${x}/100`,"Site score"]}),e.jsx(en,{type:"monotone",dataKey:"score",name:"score",stroke:"#34d399",strokeWidth:2.5,dot:{r:2.5,fill:"#34d399",strokeWidth:0},isAnimationActive:!1})]})})})]}):null,e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Scorecard"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Ranking factors",e.jsx(Ce,{text:"Each factor is scored 0–100 per page (via the aeo-audit engine), then averaged across all successfully-audited pages. Pass ≥70, partial 40–69, fail <40. Expand a row to see which pages fall short and how to fix it."})]})]}),e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Factor"}),e.jsx("th",{className:"text-right",children:"Weight"}),e.jsx("th",{className:"text-right",children:"Avg"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Pass / Partial / Fail"})]})}),e.jsx("tbody",{children:d.factors.map(x=>{const T=a===x.id,U=d.crossCuttingIssues.find(k=>k.factorId===x.id),P=T?p(x.id):[],F=x.pagesPartial+x.pagesFailing;return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:T?"bg-zinc-900/30":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-left font-medium text-zinc-200 hover:text-zinc-50","aria-expanded":T,onClick:()=>l(T?null:x.id),children:[T?e.jsx(Zn,{className:"h-3.5 w-3.5 shrink-0 text-zinc-500","aria-hidden":"true"}):e.jsx(Ss,{className:"h-3.5 w-3.5 shrink-0 text-zinc-500","aria-hidden":"true"}),x.name]})}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-500",children:[x.weight,"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-200",children:x.avgScore}),e.jsx("td",{children:e.jsx(ce,{tone:nl(x.status),children:bs(x.avgScore)})}),e.jsxs("td",{className:"tabular-nums text-zinc-400",children:[e.jsx("span",{className:"text-emerald-400",children:x.pagesPassing})," / ",e.jsx("span",{className:"text-amber-400",children:x.pagesPartial})," / ",e.jsx("span",{className:"text-rose-400",children:x.pagesFailing})]})]}),T?e.jsx("tr",{className:"bg-zinc-900/30",children:e.jsx("td",{colSpan:5,className:"px-4 pb-4 pt-0",children:e.jsxs("div",{className:"space-y-4 border-l border-zinc-800 pl-4",children:[U&&U.topRecommendations.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-1.5 text-zinc-500",children:"How to fix"}),e.jsx("ul",{className:"space-y-1",children:U.topRecommendations.map((k,R)=>e.jsxs("li",{className:"flex gap-2 text-sm text-zinc-300",children:[e.jsx("span",{className:"select-none text-zinc-600",children:"→"}),e.jsx("span",{children:k})]},R))})]}):F===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"Every audited page passes this factor."}):null,F>0?e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft mb-1.5 text-zinc-500",children:["Pages below pass (",F,")"]}),e.jsx("ul",{className:"space-y-1",children:P.slice(0,Gs).map(k=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right tabular-nums ${_s(k.score)}`,children:k.score}),e.jsx("a",{href:k.url,target:"_blank",rel:"noreferrer",className:"truncate text-zinc-300 hover:text-zinc-100",title:k.url,children:k.url})]},k.url))}),P.length>Gs?e.jsxs("p",{className:"mt-1 text-xs text-zinc-600",children:["+ ",P.length-Gs," more below pass"]}):null,v?e.jsxs("p",{className:"mt-1 text-xs text-zinc-600",children:["Showing the worst ",w.length," audited pages."]}):null]}):null]})})}):null]},x.id)})})]})})]}),d.crossCuttingIssues.length>0?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Opportunities"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Prioritized fixes",e.jsx(Ce,{text:"Factors scoring below pass across the most pages, ranked by site-wide impact. Fixing one of these typically lifts many pages at once."})]})]}),e.jsx("div",{className:"mt-3 divide-y divide-zinc-800/60 overflow-hidden rounded-lg border border-zinc-800/60",children:d.crossCuttingIssues.map(x=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:x.factorName}),e.jsx(ce,{tone:qs(x.avgScore),children:bs(x.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-zinc-500",children:["avg ",x.avgScore," · affects ",x.affectedPages," of ",x.totalPages," pages (",x.affectedPct,"%)"]})]}),x.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:x.topRecommendations.map((T,U)=>e.jsxs("li",{className:"flex gap-2 text-sm text-zinc-400",children:[e.jsx("span",{className:"select-none text-zinc-600",children:"→"}),e.jsx("span",{children:T})]},U))}):null]},x.factorId))})]}):null,e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Pages"}),e.jsx("h2",{children:"Per-page breakdown"})]}),A?e.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-800/60 p-0.5",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>i(!1),"aria-pressed":!M,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${M?"text-zinc-500 hover:text-zinc-300":"bg-zinc-800 text-zinc-100"}`,children:["All ",d.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>i(!0),"aria-pressed":M,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${M?"bg-rose-500/15 text-rose-300":"text-zinc-500 hover:text-zinc-300"}`,children:["Errors ",d.pagesErrored]})]}):null]}),E.length===0?e.jsx("p",{className:"supporting-copy mt-3",children:"No pages recorded."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right",children:"Score"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:E.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:x.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-rose-400",children:[e.jsx(Fa,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:_s(x.overallScore),children:x.overallScore})}),e.jsx("td",{children:x.status==="error"?e.jsx(ce,{tone:"negative",children:"Error"}):e.jsx(ce,{tone:qs(x.overallScore),children:bs(x.overallScore)})}),e.jsx("td",{className:"max-w-0",children:e.jsx("a",{href:x.url,target:"_blank",rel:"noreferrer",className:"block truncate text-zinc-300 hover:text-zinc-100",title:x.status==="error"?x.error??x.url:x.url,children:x.url})})]},x.url))})]})}),v?e.jsxs("p",{className:"mt-2 text-xs text-zinc-600",children:["Showing the worst ",w.length," of ",d.pagesAudited," audited pages."]}):null]})]})]})}const al={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function ke(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 rl(t){if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function cl(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function ll({projectName:t}){const[s,n]=r.useState(!1),[i,a]=r.useState(null),l=Pe(Ua({client:V,path:{name:t}}));async function o(){n(!0),a(null);try{await Qa(t,"client")}catch(m){const f=m instanceof Vs||m instanceof Error?m.message:"Download failed";a(f)}finally{n(!1)}}if(l.isLoading)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading report…"});if(l.error){const m=l.error instanceof Error?l.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-rose-400",children:m})})}const u=l.data;return u?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:u.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[u.meta.project.canonicalDomain," · ",u.meta.project.country," / ",u.meta.project.language.toUpperCase(),u.meta.location?` · Location: ${cl(u.meta.location)}`:" · No location set"," · ","Generated ",rl(u.meta.generatedAt)]}),i&&e.jsx("p",{className:"mt-2 text-xs text-rose-400",children:i})]}),e.jsx("div",{className:"page-header-right",children:e.jsxs(D,{variant:"secondary",size:"sm",onClick:X(o),disabled:s,children:[e.jsx(ts,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})})]}),e.jsx(pl,{report:u}),e.jsx(Nl,{report:u,audience:"client"}),e.jsx(xl,{report:u}),e.jsx(bl,{report:u,audience:"client",projectName:t}),e.jsx(jl,{report:u})]}):null}const Bn="AI Visibility — Server-Side",On="AI engine attention",ol="What AI engines actually do in your server logs over the last 7 days — the other half of citations.",dl="Live telemetry from your server logs.";function xl({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ns,{eyebrow:On,title:Bn,subtitle:dl}),e.jsx("p",{className:"text-sm text-zinc-500",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:sc(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},i=Rs(n,"requests"),a=`${ke(s.verifiedCrawlerHits.current)} verified · ${ke(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,l=Rs(s.aiUserFetchHits,"requests"),o=Rs(s.referralArrivals,"sessions"),u=s.byOperator.filter(m=>m.verifiedHits>0||m.unverifiedHits>0||m.userFetchHits>0||m.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ns,{eyebrow:On,title:Bn,subtitle:ol}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Ks,{label:"AI bot requests observed",value:ke(n.current),subtitle:a}),e.jsx(Ks,{label:"AI user-fetch requests",value:ke(s.aiUserFetchHits.current),subtitle:l||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Ks,{label:"AI referral sessions",value:ke(s.referralArrivals.current),subtitle:o})]}),u.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"AI tool"}),e.jsx("th",{children:"Bot requests (7d)"}),e.jsx("th",{children:"User fetches (7d)"}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:u.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:m.operator}),e.jsx("td",{children:ke(m.verifiedHits+m.unverifiedHits)}),e.jsx("td",{children:ke(m.userFetchHits)}),e.jsx("td",{children:ke(m.referralArrivals)})]},m.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-zinc-500",children:"Bot requests are bulk crawl (GPTBot, PerplexityBot, …). User fetches are on-demand reads triggered by real users inside an AI surface (ChatGPT-User, Perplexity-User, …). Verified means the request came from an IP the operator publishes as its own; unverified means the user-agent matched but the IP is not in a published range. User-fetch totals count both, since many genuine user fetches come from outside any published range."})]})]})}function ml(t,s){return t.audience==="both"||t.audience===s}const ul={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function ws(t){return ul[t]??t.charAt(0).toUpperCase()+t.slice(1)}function hl(t){if(!t)return null;const s=t.window??1,n=s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`;return t.direction==="up"?{text:`Up ${t.deltaAbs.toFixed(1)} points ${n}`,tone:"positive",arrow:"↑"}:t.direction==="down"?{text:`Down ${Math.abs(t.deltaAbs).toFixed(1)} points ${n}`,tone:"negative",arrow:"↓"}:{text:`Holding steady ${s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`}`,tone:"neutral",arrow:"→"}}function pl({report:t}){const s=t.executiveSummary,n=t.citationScorecard,i=s.totalQueryCount,a=i>0?`${s.citationRate}%`:"—",l=i>0?`When customers asked AI ${i} ${i===1?"question":"questions"} about your industry, AI linked to your website in ${s.citedQueryCount} of ${i===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer questions about your business.",o=hl(t.whatsChanged.citationRate),u=n.providers.length>0?n.providers.map(ws).join(", "):`${ke(s.queryCount)} ${s.queryCount===1?"question":"questions"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-zinc-800/60 bg-zinc-900/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-zinc-50 sm:text-7xl",children:a}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-zinc-300 sm:text-lg",children:l}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-emerald-400":o.tone==="negative"?"text-rose-400":"text-zinc-400"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(Us,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:i>0?`Says your name in ${s.mentionedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(Us,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:i>0?`Cites your site as a source in ${s.citedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(Us,{label:"AI tools tested",value:ke(s.providerCount),subtitle:u})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-semibold text-zinc-200",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-zinc-200",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-zinc-200",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Customer questions we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:["These are the ",n.queries.length," ",n.queries.length===1?"question we asked":"questions we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((m,f)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2 text-sm text-zinc-200",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-zinc-500",children:String(f+1).padStart(2,"0")}),e.jsxs("span",{children:['"',m,'"']})]},f))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"How often each AI tool links to your website"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Higher is better. Each bar shows the share of customer questions where the AI cited your site."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(m=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:ws(m.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-emerald-500/70",style:{width:`${Math.max(m.citationRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-zinc-100",children:[m.citationRate,"% ",e.jsxs("span",{className:"font-normal text-zinc-500",children:["(",m.citedCount,"/",m.totalCount,")"]})]})]},m.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((m,f)=>e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-2 text-xs text-zinc-400",children:m},f))})]})}function Us({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-zinc-50 sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",children:n})]})}function gl(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function fl(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function bl({report:t,audience:s,projectName:n}){const i=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(d=>ml(d,s)),a=ec(t,i),l=s==="client",o=Ka(),[u,m]=r.useState(new Set),f=u.size>0?a.filter(d=>!d.targetRef||!u.has(d.targetRef)):a,j=d=>{if(!d.targetRef)return;const I=d.targetRef;m(S=>new Set(S).add(I)),o.mutate({projectName:n,body:{targetRef:I}},{onSuccess:()=>{ne({tone:"positive",title:`Dismissed "${d.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:S=>{ne({tone:"negative",title:`Couldn't dismiss "${d.title}"`,detail:String(S)}),m($=>{const w=new Set($);return w.delete(I),w})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ns,{eyebrow:l?"Action plan":"Agency actions",title:l?"What to do next":"Agency Action Plan",subtitle:l?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),f.length===0?e.jsx(nn,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:f.map((d,I)=>{const S=d.evidence.length>0?d.evidence:d.why,$=d.why.length>0||d.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-zinc-800/80 text-sm font-semibold text-zinc-100",title:"Priority — 1 will move the needle fastest",children:I+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(ce,{tone:Wa(d),children:l?gl(d.horizon):Va(d.horizon)}),!l&&e.jsx(ce,{tone:"neutral",children:Ha(d.category)}),e.jsx(ce,{tone:"neutral",children:l?fl(d.confidence):`${Ya(d.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-zinc-100",children:d.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-zinc-400",children:d.action}),e.jsx(wl,{items:S,limit:3,className:"mt-3"}),$&&e.jsxs("details",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("summary",{className:"cursor-pointer text-zinc-500 hover:text-zinc-300",children:l?"See the data behind this":"Evidence details"}),d.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:l?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.why.map((w,L)=>e.jsx("li",{children:w},L))})]}),d.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:l?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.evidence.map((w,L)=>e.jsx("li",{children:w},L))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-zinc-800/60 pt-3 text-xs text-zinc-300",children:[e.jsx("span",{className:"font-medium",children:l?"What success looks like:":"Win condition:"})," ",d.successMetric]}),d.targetRef&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>j(d),className:"rounded-md border border-zinc-700/60 bg-zinc-900/50 px-2.5 py-1 text-[11px] font-medium text-zinc-300 hover:border-zinc-600 hover:bg-zinc-800/70 hover:text-zinc-100",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${d.priority}-${d.title}`)})})]})}function Fn({label:t,value:s,displayValue:n,max:i,barClass:a}){const l=i>0?Math.max(s/i*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-zinc-300",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a}`,style:{width:`${l}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-zinc-100",children:n})]})}function jl({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,i=t.indexingHealth,a=tc(t).slice(0,5),l=s.length>0?Math.max(...s.map(m=>m.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(m=>m.impressions),1):0,u=s.length>0||n!==null||i!==null||a.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ns,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),u?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"The websites AI tools cited most often when answering customer questions about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(m=>e.jsx(Fn,{label:m.domain+(m.isCompetitor?" (competitor)":""),value:m.count,displayValue:`${ke(m.count)}×`,max:l,barClass:"bg-zinc-400/70"},m.domain))})]}),i&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${i.indexedPct>=90?"text-emerald-400":i.indexedPct>=70?"text-amber-400":"text-rose-400"}`,children:[i.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[ke(i.indexed)," of ",ke(i.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${i.indexedPct>=90?"bg-emerald-500/70":i.indexedPct>=70?"bg-amber-500/70":"bg-rose-500/70"}`,style:{width:`${Math.max(i.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-medium text-zinc-200",children:ke(i.notIndexed)})," ",i.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ke(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ke(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(m=>e.jsx(Fn,{label:m.query,value:m.impressions,displayValue:`${ke(m.impressions)} ${m.impressions===1?"search":"searches"}`,max:o,barClass:"bg-sky-500/70"},m.query))})]}),a.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Customer questions where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-zinc-300",children:a.map((m,f)=>e.jsxs("li",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-zinc-100",children:m.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-zinc-400",children:[Ja(m.action),m.winnabilityClass==="ceded"&&e.jsx(ce,{tone:"caution",children:"Ceded surface"})]})]},f))})]})]}):e.jsx(nn,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}const yl=14;function tn(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function sn(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Qs({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"No prior data"})]});const i=n==="%"?"%":"",a=s.deltaAbs>0?"+":"",l=tn(s.direction),o=l==="positive"?"text-emerald-400":l==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,i," ",e.jsx("span",{className:"text-sm font-medium",children:sn(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[a,n==="%"?s.deltaAbs.toFixed(1):s.deltaAbs,i," vs ",s.prior,i]})]})}function Gn({label:t,delta:s,countLabel:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"Not enough trend data"})]});const i=s.deltaAbs>0?"+":"",a=tn(s.direction),l=a==="positive"?"text-emerald-400":a==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${l}`,children:[ke(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:sn(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[i,ke(s.deltaAbs)," ",n," vs prior ",yl," days"]})]})}function vl({movements:t,audience:s}){const n=t.filter(a=>a.direction!=="flat");if(n.length===0)return null;const i=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:i?"How each AI tool changed":"AI engine movements"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:i?"AI tool":"Engine"}),e.jsx("th",{children:i?"Was":"Prior"}),e.jsx("th",{children:i?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(a=>{const l=a.deltaAbs>0?"+":"",o=tn(a.direction),u=o==="positive"?"text-emerald-400":o==="negative"?"text-rose-400":"text-zinc-300";return e.jsxs("tr",{children:[e.jsx("td",{children:i?ws(a.provider):a.provider}),e.jsxs("td",{children:[a.prior,"%"]}),e.jsxs("td",{children:[a.current,"%"]}),e.jsxs("td",{className:u,children:[l,a.deltaAbs.toFixed(1),"% ",sn(a.direction)]})]},a.provider)})})]})})]})}function qn({insights:t,heading:s,emptyMessage:n,audience:i}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-zinc-500",children:n})]});const a=i==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!a&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:a?"What changed":"Title"}),e.jsx("th",{children:a?"Customer question":"Query"}),e.jsx("th",{children:a?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[!a&&e.jsxs("td",{children:[e.jsx(ce,{tone:al[l.severity],children:Xa(l.severity)}),l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[l.title,a&&l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsx("td",{className:"text-xs text-zinc-400",children:l.query}),e.jsx("td",{className:"text-xs text-zinc-400",children:a?ws(l.provider):l.provider})]},l.id))})]})})]})}function Nl({report:t,audience:s}){const n=t.whatsChanged,i=s==="client",a=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,l=e.jsx(ns,{eyebrow:i?"Since last check":"Section 2",title:i?"What's different since last check":"What's Changed",subtitle:i?void 0:n.headline});return a?e.jsxs("section",{className:"page-section-divider",children:[l,e.jsx(nn,{message:i?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[l,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Qs,{label:i?"AI links to your website":"Citation rate",delta:n.citationRate,unit:"%"}),e.jsx(Qs,{label:i?"AI mentions your name":"Mention rate",delta:n.mentionRate,unit:"%"}),e.jsx(Qs,{label:i?"Questions AI answered with you":"Cited queries",delta:n.citedQueryCount,unit:"count"}),e.jsx(Gn,{label:i?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:i?"visits":"clicks"}),e.jsx(Gn,{label:i?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:i?"visits":"sessions"})]}),e.jsx(vl,{movements:n.providerMovements,audience:s}),e.jsx(qn,{insights:n.wins,heading:i?"What got better":"Wins",emptyMessage:i?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(qn,{insights:n.regressions,heading:i?"What got worse":"Regressions",emptyMessage:i?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function Ks({label:t,value:s,tone:n,subtitle:i}){const a=n==="positive"?"text-emerald-400":n==="caution"?"text-amber-400":n==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${a}`,children:s}),i&&e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:i})]})}function ns({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1",children:n})]})}function wl({items:t,limit:s=3,className:n}){if(t.length===0)return null;const i=t.slice(0,s),a=t.length-i.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[i.map((l,o)=>e.jsx("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-300",children:l},o)),a>0&&e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-400",children:["+",a," more"]})]})}function nn({message:t}){return e.jsx("p",{className:"text-sm text-zinc-500 py-4 text-center",children:t})}function zl({project:t,onUpdateProject:s,onRefresh:n}){const[i,a]=r.useState(!1),[l,o]=r.useState(!1),[u,m]=r.useState(null),[f,j]=r.useState(t.displayName),[d,I]=r.useState(t.canonicalDomain),[S,$]=r.useState(t.country),[w,L]=r.useState(t.language),[A,M]=r.useState(t.ownedDomains??[]),[E,v]=r.useState(""),[p,x]=r.useState(t.aliases??[]),[T,U]=r.useState(""),[P,F]=r.useState(null),[k,R]=r.useState(!1),[_,z]=r.useState(!1),[H,oe]=r.useState(""),[he,be]=r.useState(""),[ee,ge]=r.useState(""),[Ne,g]=r.useState(""),[G,Z]=r.useState("");r.useEffect(()=>{i||(j(t.displayName),I(t.canonicalDomain),$(t.country),L(t.language),M(t.ownedDomains??[]),x(t.aliases??[]))},[t,i]);function le(){a(!1),m(null),j(t.displayName),I(t.canonicalDomain),$(t.country),L(t.language),M(t.ownedDomains??[]),x(t.aliases??[]),v(""),U("")}function ue(){const b=E.trim();b&&(A.includes(b)||M([...A,b]),v(""))}function Re(b){M(A.filter(C=>C!==b))}function we(){const b=T.trim();if(!b)return;const C=b.toLowerCase();p.some(Ae=>Ae.toLowerCase()===C)||x([...p,b]),U("")}function ae(b){x(p.filter(C=>C!==b))}async function te(){if(!(!f.trim()||!d.trim()||!S.trim()||!w.trim())){o(!0),m(null);try{await s(t.name,{displayName:f.trim(),canonicalDomain:d.trim(),ownedDomains:A,aliases:p,country:S.trim(),language:w.trim()}),a(!1),ne({title:"Project settings saved",detail:`${f.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(b){m(b instanceof Error?b.message:"Failed to save")}finally{o(!1)}}}async function je(){const b=H.trim(),C=he.trim(),Ae=ee.trim(),Te=Ne.trim();if(!(!b||!C||!Ae||!Te)){R(!0),F(null);try{const Se={label:b,city:C,region:Ae,country:Te};G.trim()&&(Se.timezone=G.trim()),await tr(t.name,Se),n(),oe(""),be(""),ge(""),g(""),Z(""),z(!1),ne({title:"Location added",detail:`${b} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${b}`,dedupeMode:"drop"})}catch(Se){F(Se instanceof Error?Se.message:"Failed to add location")}finally{R(!1)}}}async function ze(b){R(!0),F(null);try{await er(t.name,b),n(),ne({title:"Location removed",detail:`${b} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${b}`,dedupeMode:"drop"})}catch(C){F(C instanceof Error?C.message:"Failed to remove location")}finally{R(!1)}}async function fe(b){R(!0),F(null);try{await Za(t.name,b),n(),ne({title:"Default location updated",detail:`${b} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(C){F(C instanceof Error?C.message:"Failed to set default location")}finally{R(!1)}}const B=f!==t.displayName||d!==t.canonicalDomain||S!==t.country||w!==t.language||JSON.stringify(A)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(p)!==JSON.stringify(t.aliases??[]),q="w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",re="block text-xs font-medium text-zinc-400 mb-1",se=H.trim()&&he.trim()&&ee.trim()&&Ne.trim();return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!i&&e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),u&&e.jsxs("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:[u,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>m(null),children:"×"})]}),i?e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:re,children:"Display name"}),e.jsx("input",{className:q,type:"text",value:f,onChange:b=>j(b.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:re,children:"Canonical domain"}),e.jsx("input",{className:q,type:"text",value:d,onChange:b=>I(b.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:re,children:"Country"}),e.jsx("input",{className:q,type:"text",value:S,onChange:b=>$(b.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:re,children:"Language"}),e.jsx("input",{className:q,type:"text",value:w,onChange:b=>L(b.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:re,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:A.map(b=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[b,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>Re(b),"aria-label":`Remove ${b}`,children:"×"})]},b))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${q} flex-1`,type:"text",placeholder:"docs.example.com",value:E,onChange:b=>v(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),ue())}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:!E.trim(),onClick:ue,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:re,children:"Aliases"}),e.jsx("p",{className:"text-[11px] text-zinc-500 mb-1.5",children:'Additional brand names checked against LLM answer text. Use for product names, prior names, or DBAs (e.g. add "Meta" as an alias to facebook.com).'}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:p.map(b=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[b,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>ae(b),"aria-label":`Remove ${b}`,children:"×"})]},b))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${q} flex-1`,type:"text",placeholder:"Facebook",value:T,onChange:b=>U(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),we())}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:!T.trim(),onClick:we,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-zinc-800/60",children:[e.jsx(D,{type:"button",disabled:l||!B||!f.trim()||!d.trim(),onClick:X(te),children:l?"Saving...":"Save changes"}),e.jsx(D,{type:"button",variant:"outline",disabled:l,onClick:le,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(b=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:b},b))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(b=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:b},b))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.country})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[P&&e.jsxs("div",{className:"mb-2 rounded border border-rose-800/40 bg-rose-950/20 px-2 py-1 text-xs text-rose-300",children:[P,e.jsx("button",{type:"button",className:"ml-1 text-rose-400 hover:text-rose-200",onClick:()=>F(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-zinc-600",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(b=>e.jsxs("tr",{className:"border-t border-zinc-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium ${b.label===t.defaultLocation?"border-emerald-700/60 bg-emerald-950/30 text-emerald-300":"border-zinc-700/60 bg-zinc-800/40 text-zinc-300"}`,children:[b.label,b.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:b.city}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:b.region}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:b.country}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500",children:b.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[b.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:k,onClick:()=>{fe(b.label)},className:"text-[10px] text-zinc-500 hover:text-emerald-400 transition-colors disabled:opacity-40","aria-label":`Set ${b.label} as default location`,children:"Set default"}),e.jsx("button",{type:"button",disabled:k,onClick:()=>{ze(b.label)},className:"text-[10px] text-zinc-500 hover:text-rose-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${b.label}`,children:"Remove"})]})})]},b.label))})]}):e.jsx("p",{className:"text-zinc-500 text-xs mb-2",children:"No locations configured"}),_?e.jsxs("div",{className:"mt-2 rounded border border-zinc-800 bg-zinc-900/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-zinc-500",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Label *"}),e.jsx("input",{className:q,type:"text",value:H,onChange:b=>oe(b.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"City *"}),e.jsx("input",{className:q,type:"text",value:he,onChange:b=>be(b.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Region *"}),e.jsx("input",{className:q,type:"text",value:ee,onChange:b=>ge(b.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Country *"}),e.jsx("input",{className:q,type:"text",value:Ne,onChange:b=>g(b.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Timezone (optional)"}),e.jsx("input",{className:q,type:"text",value:G,onChange:b=>Z(b.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(D,{type:"button",size:"sm",disabled:k||!se,onClick:X(je),children:k?"Adding...":"Add location"}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:k,onClick:()=>{z(!1),F(null)},children:"Cancel"})]})]}):e.jsx(D,{type:"button",size:"sm",variant:"outline",onClick:()=>z(!0),children:"+ Add location"})]})]})]})})})]})}const Sl=[{value:"daily",label:"Every day"},{value:"weekly@mon",label:"Every Monday"},{value:"weekly@wed",label:"Every Wednesday"},{value:"weekly@fri",label:"Every Friday"},{value:"twice-daily",label:"Twice a day (6am & 6pm)"},{value:"custom",label:"Custom cron expression"}],_n=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Vancouver","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Australia/Sydney"];function kl({projectName:t}){const[s,n]=r.useState("loading"),[i,a]=r.useState(!1),[l,o]=r.useState("daily"),[u,m]=r.useState(6),[f,j]=r.useState(""),[d,I]=r.useState("UTC"),[S,$]=r.useState(!1),[w,L]=r.useState(""),[A,M]=r.useState(!1),[E,v]=r.useState(!1),[p,x]=r.useState(null);r.useEffect(()=>{sr(t).then(n).catch(()=>n(null))},[t]);const T=()=>{if(s&&s!=="loading"){const k=ir(s.preset??null,s.cronExpr);o(k.freq),m(k.hour),j(k.customCron);const R=_n.includes(s.timezone);I(R?s.timezone:"Other"),$(!R),L(R?"":s.timezone)}else o("daily"),m(6),j(""),I("UTC"),$(!1),L("");x(null),a(!0)},U=async()=>{M(!0),x(null);try{const R={timezone:S?w.trim()||"UTC":d};l==="custom"?R.cron=f.trim():R.preset=rr(l,u);const _=await bn(t,R);n(_),a(!1),ne({title:"Schedule saved",detail:Is(_.preset??null,_.cronExpr,_.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(k){x(k instanceof Error?k.message:"Failed to save schedule")}finally{M(!1)}},P=async()=>{if(!(!s||s==="loading")){M(!0),x(null);try{const k={timezone:s.timezone,enabled:!s.enabled};s.preset?k.preset=s.preset:k.cron=s.cronExpr;const R=await bn(t,k);n(R),ne({title:R.enabled?"Schedule resumed":"Schedule paused",detail:Is(R.preset??null,R.cronExpr,R.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(k){x(k instanceof Error?k.message:"Failed to update schedule")}finally{M(!1)}}},F=async()=>{v(!0),x(null);try{await ar(t),n(null),a(!1),ne({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(k){x(k instanceof Error?k.message:"Failed to remove schedule")}finally{v(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),s!=="loading"&&!i&&e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:T,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!i&&s===null&&e.jsx(K,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),s!=="loading"&&!i&&s!==null&&e.jsxs(K,{className:"surface-card compact-card",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:Is(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ce,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:A,onClick:X(P),children:s.enabled?"Pause":"Resume"}),e.jsx(D,{type:"button",variant:"ghost",size:"sm",disabled:E,onClick:X(F),children:E?"Removing...":"Remove"})]})]}),p&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:p})]}),i&&e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/40 p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:l,onChange:k=>o(k.target.value),children:Sl.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none disabled:opacity-40",value:u,disabled:l==="twice-daily"||l==="custom",onChange:k=>m(parseInt(k.target.value)),children:Array.from({length:24},(k,R)=>e.jsx("option",{value:R,children:nr(R)},R))})]})]}),l==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 font-mono focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:f,onChange:k=>j(k.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:S?"Other":d,onChange:k=>{k.target.value==="Other"?($(!0),I("Other")):($(!1),I(k.target.value))},children:[_n.map(k=>e.jsx("option",{value:k,children:k},k)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),S&&e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:w,onChange:k=>L(k.target.value)})]}),p&&e.jsx("p",{className:"text-rose-400 text-sm",children:p}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),x(null)},children:"Cancel"}),e.jsx(D,{type:"button",size:"sm",disabled:A||l==="custom"&&!f.trim(),onClick:X(U),children:A?"Saving...":"Save schedule"})]})]})]})}const Cl=[{value:"citation.lost",label:"Citation lost"},{value:"citation.gained",label:"Citation gained"},{value:"run.completed",label:"Run completed"},{value:"run.failed",label:"Run failed"}];function Al({projectName:t}){const[s,n]=r.useState("loading"),[i,a]=r.useState(!1),[l,o]=r.useState(""),[u,m]=r.useState(["citation.lost","citation.gained"]),[f,j]=r.useState(!1),[d,I]=r.useState(null),[S,$]=r.useState({}),[w,L]=r.useState(new Set);r.useEffect(()=>{cr(t).then(n).catch(()=>n([]))},[t]);const A=p=>{m(x=>x.includes(p)?x.filter(T=>T!==p):[...x,p])},M=async()=>{if(!(!l.trim()||u.length===0)){j(!0),I(null);try{const p=await lr(t,{channel:"webhook",url:l.trim(),events:u});n(x=>x==="loading"?[p]:[...x,p]),o(""),m(["citation.lost","citation.gained"]),a(!1),ne({title:"Webhook added",detail:`Notifications will be sent to ${p.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(p){I(p instanceof Error?p.message:"Failed to add webhook")}finally{j(!1)}}},E=async p=>{if(!w.has(p)){L(x=>new Set(x).add(p));try{await dr(t,p),n(x=>x==="loading"?x:x.filter(T=>T.id!==p)),ne({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${p}`,dedupeMode:"drop"})}catch(x){I(x instanceof Error?x.message:"Failed to remove webhook")}finally{L(x=>{const T=new Set(x);return T.delete(p),T})}}},v=async p=>{$(x=>({...x,[p]:{state:"testing"}}));try{const x=await or(t,p);$(T=>({...T,[p]:{state:x.ok?"ok":"fail",status:x.status}})),x.ok&&ne({title:"Test notification sent",detail:`Webhook returned status ${x.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${p}`,dedupeMode:"replace"})}catch{$(x=>({...x,[p]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),s!=="loading"&&e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!i),I(null)},children:i?"Cancel":"+ Add webhook"})]}),i&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:p=>o(p.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Cl.map(p=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-zinc-600 bg-zinc-800",checked:u.includes(p.value),onChange:()=>A(p.value)}),e.jsx("span",{className:"text-sm text-zinc-300",children:p.label})]},p.value))})]}),d&&e.jsx("p",{className:"text-rose-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),I(null)},children:"Cancel"}),e.jsx(D,{type:"button",size:"sm",disabled:f||!l.trim()||u.length===0,onClick:X(M),children:f?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!i&&e.jsx(K,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-zinc-300 break-all",title:p.urlHost,children:p.urlDisplay??p.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:p.events.map(x=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-zinc-700 bg-zinc-800/60 px-2 py-0.5 text-[10px] font-medium text-zinc-400 uppercase tracking-wide",children:x.replace("."," ")},x))})}),e.jsx("td",{children:e.jsx(ce,{tone:p.enabled?"positive":"neutral",children:p.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[S[p.id]&&(()=>{const x=S[p.id],T=x.state==="testing"?"Sending…":x.state==="ok"?`Delivered${x.status?` (${x.status})`:""}`:`Failed${x.status?` (${x.status})`:""}`;return e.jsx(ce,{tone:x.state==="ok"?"positive":x.state==="fail"?"negative":"neutral",children:T})})(),e.jsx(D,{variant:"ghost",size:"sm",type:"button",disabled:S[p.id]?.state==="testing",onClick:()=>{v(p.id)},children:"Test"}),e.jsx(D,{variant:"ghost",size:"sm",type:"button",disabled:w.has(p.id),onClick:()=>{E(p.id)},children:w.has(p.id)?"Removing…":"Remove"})]})})]},p.id))})]}),d&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:d})]})]})}function Tt(t,s){return t.invalidateQueries({predicate:n=>{const i=n.queryKey[0];return typeof i?._id=="string"&&i._id.startsWith(s)}})}function Dl({projectName:t,refreshNonce:s}){const n=bt(),[i,a]=r.useState(null),[l,o]=r.useState([]),[u,m]=r.useState(null),[f,j]=r.useState([]),[d,I]=r.useState([]),[S,$]=r.useState(null),[w,L]=r.useState(""),[A,M]=r.useState(""),[E,v]=r.useState(""),[p,x]=r.useState(!0),[T,U]=r.useState(!1),[P,F]=r.useState(null),[k,R]=r.useState("performance");r.useEffect(()=>{_()},[t,s]);async function _(){x(!0),F(null);try{const g=await n.fetchQuery({...ei({client:V,path:{name:t}}),staleTime:$e});if(a(g),g.connected){const[G,Z,le,ue]=await Promise.all([n.fetchQuery({...ti({client:V,path:{name:t}}),staleTime:$e}).catch(()=>null),n.fetchQuery({...si({client:V,path:{name:t}}),staleTime:$e}).catch(()=>[]),n.fetchQuery({...Lr({client:V,path:{name:t}}),staleTime:$e}).catch(()=>[]),g.siteUrl?Promise.resolve([]):n.fetchQuery({...$r({client:V,path:{name:t}}),staleTime:$e}).then(Re=>Re.sites).catch(()=>[])]);m(G),j(Z),I(le),o(ue)}else m(null),j([]),I([]),o([])}catch(g){F(g instanceof Error?g.message:"Failed to load Bing data")}finally{x(!1)}}async function z(){if(A.trim()){F(null);try{const g=await Ir(t,A.trim());await Tt(n,"getApiV1ProjectsByNameBing"),M(""),g.availableSites.length>0&&o(g.availableSites),await _()}catch(g){F(g instanceof Error?g.message:"Failed to connect")}}}async function H(){try{await Pr(t),await Tt(n,"getApiV1ProjectsByNameBing"),a(null),o([]),m(null),j([]),I([]),$(null),v(""),F(null)}catch(g){F(g instanceof Error?g.message:"Failed to disconnect")}}async function oe(){if(E)try{await Rr(t,E),await Tt(n,"getApiV1ProjectsByNameBing"),await _()}catch(g){F(g instanceof Error?g.message:"Failed to set site")}}async function he(){if(w.trim())try{const g=await ni(t,w.trim());await Tt(n,"getApiV1ProjectsByNameBing"),$(g),j(G=>[g,...G])}catch(g){F(g instanceof Error?g.message:"Inspection failed")}}async function be(g){U(!0),F(null);try{const G=await Nn(t,{urls:[g]}),{succeeded:Z,failed:le,total:ue}=G.summary;ne({title:"Bing submission requested",detail:le===0?`${Z} URL submitted to Bing.`:`${Z}/${ue} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${g}`,dedupeMode:"replace"})}catch(G){const Z=G instanceof Error?G.message:"Submission failed";F(Z),ne({title:"Bing submission failed",detail:Z,tone:"negative",dedupeKey:`bing:indexing:${t}:${g}`,dedupeMode:"replace"})}finally{U(!1)}}async function ee(){U(!0),F(null),ne({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const g=await Nn(t,{allUnindexed:!0}),{succeeded:G,failed:Z,total:le}=g.summary;ne({title:"Bing submissions requested",detail:Z===0?`${G}/${le} URL${le!==1?"s":""} submitted to Bing.`:`${G}/${le} submitted successfully, ${Z} failed.`,tone:Z===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(g){const G=g instanceof Error?g.message:"Batch submission failed";F(G),ne({title:"Bing submissions failed",detail:G,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{U(!1)}}if(p)return e.jsx(K,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-zinc-400",children:"Loading Bing data..."})});if(!i?.connected)return e.jsxs(K,{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(ce,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-zinc-300",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-zinc-500",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:A,onChange:g=>M(g.target.value),onKeyDown:g=>{g.key==="Enter"&&z()}}),e.jsx(D,{size:"sm",disabled:!A.trim(),onClick:X(z),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-zinc-400 hover:text-zinc-300 underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),P&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:P})]});if(!i.siteUrl)return e.jsxs(K,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"positive",children:"Connected"}),e.jsx(D,{size:"sm",variant:"ghost",onClick:X(H),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.domain})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?Xe(i.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Select site"}),l.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:E,onChange:g=>v(g.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(g=>e.jsxs("option",{value:g.url,children:[g.url,g.verified?" (verified)":""]},g.url))]}),e.jsx(D,{size:"sm",disabled:!E,onClick:X(oe),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-zinc-500",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),P&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:P})]});const ge=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],Ne=ge.find(g=>g.key===k)??ge[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(K,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{tone:"positive",children:"Connected"}),e.jsx(D,{size:"sm",variant:"ghost",onClick:X(H),children:"Disconnect"})]})]}),P&&e.jsx("p",{className:"mb-3 text-xs text-rose-400",children:P}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:["Canonry stores Bing connections per canonical domain. This project is currently mapped to ",e.jsx("code",{children:i.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?Xe(i.updatedAt):"—"})]})]})]})]}),e.jsxs(K,{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:Ne.eyebrow}),e.jsx("h3",{children:Ne.title})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:u?.lastInspectedAt?`Last inspected ${Xe(u.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-zinc-800",children:ge.map(g=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${k===g.key?"border-zinc-200 text-zinc-200":"border-transparent text-zinc-500 hover:text-zinc-300"}`,onClick:()=>R(g.key),children:g.label},g.key))}),k==="coverage"&&u&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(us,{label:"Indexed",value:u.summary.indexed,tone:"positive"}),e.jsx(us,{label:"Not in index",value:u.summary.notIndexed+(u.summary.unknown??0),tone:"negative"}),e.jsx(us,{label:"Status unknown",value:u.summary.unknown??0,tone:"neutral"}),e.jsx(us,{label:"Coverage",value:`${u.summary.percentage}%`,tone:"neutral"})]}),u.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-zinc-400",children:["Not Indexed (",u.notIndexed.length,")"]}),e.jsx(D,{size:"sm",variant:"ghost",disabled:T,onClick:X(ee),children:T?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"HTTP"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:u.notIndexed.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:T,onClick:()=>{be(g.url)},children:"Submit"})})]},g.id))})]})})]}),(u.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-zinc-400",children:["Unknown — not yet confirmed (",(u.unknown??[]).length,")"]}),e.jsx(D,{size:"sm",variant:"ghost",disabled:T,onClick:X(ee),children:T?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(u.unknown??[]).map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.lastCrawledDate?Xe(g.lastCrawledDate):"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:T,onClick:()=>{be(g.url)},children:"Submit"})})]},g.id))})]})})]}),u.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-zinc-400",children:["Indexed (",u.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:u.indexed.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.lastCrawledDate?Xe(g.lastCrawledDate):"—"})]},g.id))})]})})]})]}),k==="coverage"&&!u&&e.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"No coverage data yet. Inspect URLs to build coverage data."}),k==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"URL to inspect",value:w,onChange:g=>L(g.target.value),onKeyDown:g=>{g.key==="Enter"&&he()}}),e.jsx(D,{size:"sm",disabled:!w.trim(),onClick:X(he),children:"Inspect"})]}),S&&e.jsxs("div",{className:"rounded border border-zinc-800 bg-zinc-900/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-zinc-200",children:S.url}),e.jsxs("div",{className:"text-zinc-400",children:["In Index: ",e.jsx("span",{className:S.inIndex?"text-emerald-400":"text-rose-400",children:S.inIndex?"Yes":"No"})," · ","HTTP: ",S.httpCode??"—"," · ","Crawled: ",S.lastCrawledDate??"—"]})]}),f.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:f.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ce,{tone:g.inIndex?"positive":"negative",children:g.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:Xe(g.inspectedAt)})]},g.id))})]})})]}),k==="performance"&&e.jsx("div",{className:"mt-4",children:d.length===0?e.jsx("p",{className:"text-xs text-zinc-500",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:ms[zt.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:ms[zt.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:ms[zt.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:ms[zt.Position]})]})}),e.jsx("tbody",{children:d.map((g,G)=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-200",children:g.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:g.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:[(Number.isFinite(g.ctr)?g.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:g.averagePosition.toFixed(1)})]},G))})]})})})]})]})}function Ll({projectName:t}){const s=bt(),[n,i]=r.useState("google"),[a,l]=r.useState(!0),[o,u]=r.useState("idle"),[m,f]=r.useState(null),j=r.useRef(null),[d,I]=r.useState(!1),[S,$]=r.useState(null),[w,L]=r.useState(null),[A,M]=r.useState(!1),[E,v]=r.useState(null),[p,x]=r.useState(null),[T,U]=r.useState(0);async function P(g=!1){g||l(!0),f(null);try{const[G,Z,le]=await Promise.all([s.fetchQuery(Cr({client:V})).catch(()=>null),s.fetchQuery({...Js({client:V,path:{name:t}}),staleTime:$e}).catch(()=>[]),s.fetchQuery({...ei({client:V,path:{name:t}}),staleTime:$e}).catch(()=>null)]),ue=Z.find(ae=>ae.connectionType==="gsc")??null;I(!!G?.google?.configured),M(!!G?.bing?.configured),$(ue),v(le);const[Re,we]=await Promise.all([ue?s.fetchQuery({...Vn({client:V,path:{name:t}}),staleTime:$e}).catch(()=>null):Promise.resolve(null),le?.connected?s.fetchQuery({...ti({client:V,path:{name:t}}),staleTime:$e}).catch(()=>null):Promise.resolve(null)]);L(Re),x(we)}catch(G){f(G instanceof Error?G.message:"Failed to load search console overview")}finally{l(!1)}}async function F(){if(o!=="idle")return;j.current?.abort();const g=new AbortController;j.current=g;const G=g.signal;u("syncing"),f(null);const Z=[];try{async function le(){if(!S)return;const ae=await Ar(t);if(!ae?.id)return;const te=2e3,ze=Date.now()+12e4;for(;Date.now()<ze;){if(G.aborted||(await new Promise(B=>setTimeout(B,te)),G.aborted))return;const fe=await Hn(ae.id).catch(()=>null);if(!fe)break;if(["completed","failed","cancelled"].includes(fe.status)){fe.status!=="completed"&&Z.push(`Google sync ${fe.status}`);break}}}const ue=10;async function Re(){if(!E?.connected)return;const ae=await s.fetchQuery({...si({client:V,path:{name:t}}),staleTime:0}).catch(()=>[]),te=[...new Set(ae.map(je=>je.url))];if(te.length===0){await Dr(t).catch(()=>null);return}for(let je=0;je<te.length;je+=ue){if(G.aborted)return;const ze=te.slice(je,je+ue),B=(await Promise.allSettled(ze.map(q=>ni(t,q)))).filter(q=>q.status==="rejected").length;B>0&&Z.push(`${B} Bing inspection(s) failed`)}}const we=await Promise.allSettled([le(),Re()]);for(const ae of we)ae.status==="rejected"&&Z.push(ae.reason instanceof Error?ae.reason.message:"Sync failed");if(G.aborted)return;u("reloading"),await Promise.all([Tt(s,"getApiV1ProjectsByNameGoogleGsc"),Tt(s,"getApiV1ProjectsByNameBing")]),await P(!0),U(ae=>ae+1),Z.length>0&&f(`Partial refresh: ${Z.join("; ")}`)}catch(le){G.aborted||f(le instanceof Error?le.message:"Refresh failed")}finally{G.aborted||u("idle")}}r.useEffect(()=>(P(),()=>{j.current?.abort()}),[t]);const k=S?"positive":d?"caution":"negative",R=S?"Connected":d?"Ready to connect":"Needs setup",_=w?`${w.summary.percentage}% indexed`:S?"Awaiting coverage":"No coverage data",z=w?`${w.summary.notIndexed} not indexed${w.summary.deindexed>0?` · ${w.summary.deindexed} deindexed`:""}`:S?"Run sitemap inspection to populate coverage":d?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",H=w?.lastSyncedAt??w?.lastInspectedAt??S?.updatedAt??null,oe=E?.connected?"positive":A?"caution":"negative",he=E?.connected?"Connected":A?"Ready to connect":"Needs setup",be=p?`${p.summary.percentage}% indexed`:E?.connected?"Awaiting coverage":"No coverage data",ee=p?p.summary.notIndexed+(p.summary.unknown??0):0,ge=p?`${ee} not in index`:E?.connected?"Inspect URLs to populate coverage":A?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings",Ne=p?.lastInspectedAt??E?.updatedAt??null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(K,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engines"}),e.jsx("h2",{children:"Coverage & performance"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-500",children:"Scan both engines at a glance, then open the Google or Bing workspace when you need to inspect coverage or take action."})]}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:a||o!=="idle",onClick:()=>{F()},children:a?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"})]}),m&&e.jsx("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:m}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(Cn,{eyebrow:"Google",title:"Google Search Console",status:a?"Loading…":R,tone:a?"neutral":k,targetLabel:"Selected property",targetValue:S?.propertyId??"No property selected",coverageValue:a?"Loading…":_,note:a?"Loading overview…":z,updatedAt:H,active:n==="google",onClick:()=>i("google")}),e.jsx(Cn,{eyebrow:"Bing",title:"Bing Webmaster Tools",status:a?"Loading…":he,tone:a?"neutral":oe,targetLabel:"Selected site",targetValue:E?.siteUrl??"No site selected",coverageValue:a?"Loading…":be,note:a?"Loading overview…":ge,updatedAt:Ne,active:n==="bing",onClick:()=>i("bing")})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([g,G])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===g,className:`project-subnav-link ${n===g?"project-subnav-link-active":""}`,onClick:()=>i(g),children:G},g))}),n==="google"&&e.jsx(Sc,{projectName:t,refreshNonce:T}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Dl,{projectName:t,refreshNonce:T})]})]})}function $l({summary:t,onJumpToEvidence:s}){if(!t.hasPreviousRun)return e.jsxs("section",{className:"movement-banner",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),e.jsx("span",{className:"text-zinc-500",children:"First run — no comparison yet"})]});const n=t.gained,i=t.lost,a=n===0&&i===0?"· no changes":n>i?"· improving":i>n?"· declining":"";return e.jsxs("section",{className:"movement-banner",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),n>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-emerald-400 font-medium",onClick:s,title:"Jump to the queries that gained citations",children:["+",n," gained"]}):e.jsx("span",{className:"text-zinc-500",children:"+0 gained"}),e.jsx("span",{className:"text-zinc-700 mx-1",children:"·"}),i>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-rose-400 font-medium",onClick:s,title:"Jump to the queries that lost citations",children:["−",i," lost"]}):e.jsx("span",{className:"text-zinc-500",children:"−0 lost"}),e.jsx("span",{className:"text-zinc-400 ml-2",children:a})]}),t.gainedQueries?.length||t.lostQueries?.length?e.jsxs("div",{className:"movement-banner-detail",children:[t.gainedQueries&&t.gainedQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-emerald-500/90",children:"Gained:"})," ",e.jsx("span",{className:"text-zinc-300",children:Un(t.gainedQueries)})]}),t.lostQueries&&t.lostQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-rose-500/90",children:"Lost:"})," ",e.jsx("span",{className:"text-zinc-300",children:Un(t.lostQueries)})]})]}):null]})}function Un(t,s=4){return t.length<=s?t.map(i=>`"${i}"`).join(", "):`${t.slice(0,s).map(i=>`"${i}"`).join(", ")}, and ${t.length-s} more`}function Il({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const i=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(i===0)return null;const a=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(o=>({label:o.domain,mentions:o.mentionSnapshots,isYou:!1}))].sort((o,u)=>u.mentions-o.mentions),l=a[0]?.mentions??1;return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsx("p",{className:"mention-share-breakdown-title",children:"Mention share breakdown · latest run"}),e.jsx("ul",{className:"mention-share-breakdown-rows",children:a.map(o=>{const u=o.mentions/i*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${o.isYou?"text-zinc-100 font-medium":"text-zinc-400"}`,children:o.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${o.isYou?"bg-emerald-500/70":"bg-zinc-500/60"}`,style:{width:`${Math.max(o.mentions/l*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:o.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[u.toFixed(1),"%"]})]},o.label)})})]})}const Pl={write:{title:"Write or update content",subtitle:"Queries with no answer, persistent gaps, or competitors winning the spot"},investigate:{title:"Investigate what changed",subtitle:"Citations or mentions you lost since the previous run"},monitor:{title:"Keep monitoring",subtitle:"Gains, new providers picking you up, holding ground"}};function Rl({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:i}=Qn(),[a,l]=r.useState(null),o=s.rows.length>0;if(t.length===0&&!o)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No outstanding opportunities. Trigger a sweep to surface fresh signals."});const u=["write","investigate","monitor"],m=new Map;for(const f of t){const j=m.get(f.actionGroup)??[];j.push(f),m.set(f.actionGroup,j)}return e.jsxs("div",{className:"opportunities-grid",children:[u.map(f=>{const j=m.get(f);if(!j||j.length===0)return null;const d=Pl[f];return e.jsxs("div",{className:`opportunity-card opportunity-card-${f}`,children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:d.title}),e.jsx("span",{className:"opportunity-card-count",children:j.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:d.subtitle}),e.jsx("div",{className:"opportunity-card-list",children:j.map(I=>{const S=a===I.id,$=I.affectedPhrases.length>0;return e.jsxs("div",{children:[e.jsx("div",{className:`opportunity-item opportunity-item-${I.tone} ${$?"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400":""}`,onClick:$?()=>l(S?null:I.id):void 0,onKeyDown:$?w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),l(S?null:I.id))}:void 0,tabIndex:$?0:void 0,role:$?"button":void 0,"aria-expanded":$?S:void 0,children:e.jsxs("div",{className:"flex items-start gap-1.5 min-w-0",children:[$&&e.jsx(Ss,{size:12,className:`mt-1 shrink-0 text-zinc-500 transition-transform duration-150 ${S?"rotate-90":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-100 leading-snug",children:I.title}),I.detail&&e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:I.detail})]})]})}),S&&e.jsx("div",{className:"opportunity-item-detail",children:I.affectedPhrases.map((w,L)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx(Ws,{state:w.citationState}),e.jsx("span",{className:"text-xs text-zinc-300 truncate",children:w.query}),w.provider&&e.jsx(Ot,{provider:w.provider})]}),w.evidenceId&&e.jsx("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 whitespace-nowrap",onClick:A=>{A.stopPropagation(),i(w.evidenceId)},children:"View →"})]},w.evidenceId||`${I.id}-${L}`))})]},I.id)})})]},f)}),o&&e.jsx(Tl,{suggestedQueries:s,projectName:n})]})}function Tl({suggestedQueries:t,projectName:s}){const n=kr(),[i,a]=r.useState(new Set),l=j=>{a(d=>new Set(d).add(j)),n.mutate({projectName:s,queries:[j]},{onSuccess:()=>{ne({tone:"positive",title:`Tracking "${j}"`}),a(d=>{const I=new Set(d);return I.delete(j),I})},onError:d=>{ne({tone:"negative",title:`Couldn't add "${j}"`,detail:String(d)}),a(I=>{const S=new Set(I);return S.delete(j),S})}})},{rows:o,totalCandidates:u,skippedAlreadyTracked:m}=t,f=m>0?`GSC queries you're getting impressions for · ${m} already tracked`:"GSC queries you're getting impressions for but aren't tracking yet";return e.jsxs("div",{className:"opportunity-card opportunity-card-track",children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:"Track new queries"}),e.jsx("span",{className:"opportunity-card-count",children:u>o.length?`${o.length} of ${u}`:o.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:f}),e.jsx("div",{className:"opportunity-card-list",children:o.map(j=>{const d=i.has(j.query);return e.jsxs("div",{className:"opportunity-item opportunity-item-neutral flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-100 leading-snug truncate",title:j.query,children:j.query}),e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:j.reason})]}),e.jsx("button",{type:"button",className:"suggested-query-add",disabled:d,onClick:()=>l(j.query),children:d?"Adding…":"+ Track"})]},j.query)})})]})}function Vl(t){const{projectId:s}=Ai({from:"/projects/$projectId"}),i=xr()?.dashboard.projects.find(d=>d.project.id===s)?.project.name??null,a=Pe({...mr({client:V}),enabled:!i}),l=i??a.data?.find(d=>d.id===s)?.name??null,{commandCenter:o,isLoading:u,refetch:m}=ur(l),f=!i&&a.isLoading||u;return!l&&!i&&a.isSuccess&&!u?e.jsx("div",{className:"page-container",children:e.jsxs(K,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project with ID "',s,'".']}),e.jsx(D,{asChild:!0,children:e.jsx(gt,{to:"/",children:"Return to overview"})})]})}):!o||f?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(d=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},d))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(d=>e.jsx("div",{className:"skeleton-text-sm w-full"},d))})]})]}):e.jsx(Ml,{model:o,refetch:m,...t})}function El({items:t,activeTab:s}){const[n,i]=r.useState(!1),a=r.useRef(null);if(r.useEffect(()=>{if(!n)return;const o=m=>{a.current&&!a.current.contains(m.target)&&i(!1)},u=m=>{m.key==="Escape"&&i(!1)};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const l=t.some(o=>o.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:a,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${l?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>i(o=>!o),children:["More",e.jsx(Zn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(o=>e.jsx(gt,{to:o.href,role:"menuitem",className:`project-subnav-menu-item ${o.key===s?"project-subnav-menu-item-active":""}`,"aria-current":o.key===s?"page":void 0,onClick:()=>i(!1),children:o.label},o.key))}):null]})}function Ml({tab:t,model:s,refetch:n}){const i=Di(),a=bt(),[l,o]=r.useState(!1),[u,m]=r.useState(!1),[f,j]=r.useState(!1),[d,I]=r.useState(""),[S,$]=r.useState(!1),[w,L]=r.useState(null),[A,M]=r.useState(!1),[E,v]=r.useState(""),[p,x]=r.useState(!1),[T,U]=r.useState(!1),[P,F]=r.useState(""),[k,R]=r.useState(!1),[_,z]=r.useState(!1),[H,oe]=r.useState(""),[he,be]=r.useState(!1),[ee,ge]=r.useState(void 0),[Ne,g]=r.useState(!1),[G,Z]=r.useState(null),[le,ue]=r.useState(null),[Re,we]=r.useState(!1),ae=s?.visibilityEvidence??[],te=s?.project.name??"",je=s?.project.displayName||s?.project.name||te,ze=hr(),fe=(s?.recentRuns??[]).some(h=>h.kind===js["answer-visibility"]&&(h.status===jn.running||h.status===jn.queued)),B=r.useMemo(()=>(s?.project.locations??[]).map(h=>h.label),[s?.project.locations]),q=r.useMemo(()=>new Set(ae.map(h=>h.location??"")),[ae]),re=q.has(""),se=r.useMemo(()=>[...new Set(ae.map(h=>h.query))].sort((h,W)=>h.localeCompare(W)),[ae]),b=r.useMemo(()=>{const h=[...q].filter(Boolean);return h.length>1?h:B},[q,B]);r.useEffect(()=>{if(ee===void 0||ee===""||!te){ue(null),we(!1);return}we(!0),pr(te,ee).then(h=>{ue(h),we(!1)}).catch(()=>{ue(null),we(!1)})},[ee,te]);const C=r.useMemo(()=>{if(!le)return null;const h=new Map;for(const W of le){for(const[de,Me]of Object.entries(W.providerRuns??{}))h.set(`${W.query}::${de}`,Me.map(xe=>({runId:xe.runId,citationState:xe.citationState,createdAt:xe.createdAt,answerMentioned:xe.answerMentioned,visibilityState:xe.visibilityState,visibilityTransition:xe.visibilityTransition,mentionState:xe.mentionState,mentionTransition:xe.mentionTransition})));(!W.providerRuns||Object.keys(W.providerRuns).length===0)&&h.set(`${W.query}::`,W.runs.map(de=>({runId:de.runId,citationState:de.citationState,createdAt:de.createdAt,answerMentioned:de.answerMentioned,visibilityState:de.visibilityState,visibilityTransition:de.visibilityTransition,mentionState:de.mentionState,mentionTransition:de.mentionTransition})))}return h},[le]),Ae=r.useMemo(()=>{let h=ee!==void 0?ae.filter(W=>ee===""?!W.location:W.location===ee):ae;if(G){const W=G.toLowerCase();h=h.filter(de=>de.competitorDomains.some(Me=>Me.toLowerCase()===W))}return C?h.map(W=>{const de=C.get(`${W.query}::${W.provider}`)??C.get(`${W.query}::`);return de?{...W,runHistory:de}:W}):h},[ae,ee,G,C]);async function Te(){try{await ze.mutateAsync({projectName:te,projectLabel:je,sourceAction:"project-run"}),n()}catch{}}async function Se(){m(!0);try{await br(te),ne({title:"Project deleted",detail:`${je} was removed.`,tone:"positive",dedupeKey:`project:delete:${te}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(h){console.error("Failed to delete project:",h)}finally{m(!1)}}async function jt(){try{const h=await jr(te),W=typeof h=="string"?h:JSON.stringify(h,null,2),de=new Blob([W],{type:"text/yaml"}),Me=URL.createObjectURL(de),xe=document.createElement("a");xe.href=Me,xe.download=`${te}.yaml`,xe.click()}catch(h){ne({title:"Export failed",detail:h instanceof Error?h.message:"Could not export project YAML.",tone:"negative"})}}async function lt(){const h=d.split(`