@ainyc/canonry 4.106.0 → 4.106.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{j as e,r,L as ft,n as yt,u as $e,o as ls,A as Xi,B as Ji,h as Zi}from"./vendor-tanstack-Be8JdV5M.js";import{c as Ts,T as ie,t as ea,a as ta,u as ci,C as sa,b as Is,P as Ht,B as P,h as na,d as ia,e as aa,f as Je,g as W,i as ee,I as Se,j as ss,k as ra,l as K,m as ca,n as la,o as oa,p as da,q as li,r as xa,s as ma,S as At,v as ua,w as ha,x as pa,y as Bt,z as ga,A as $n,D as fa,G as Re,E as un,F as ba,H as ja,J as ya,K as va,L as Na,M as re,N as Pn,O as oi,Q as wa,R as za,U as Sa,V as ka,W as Ca,X as Aa,Y as $a,Z as Pa,_ as La,$ as Da,a0 as Ta,a1 as Ia,a2 as Ra,a3 as Ea,a4 as Ma,a5 as Oa,a6 as os,a7 as Fa,a8 as Ba,a9 as Ln,aa as qa,ab as Ga,ac as _a,ad as Ua,ae as $s,af as Qa,ag as Ka,ah as Ha,ai as Wa,aj as cn,ak as Va,al as Ya,am as Xa,an as Ja,ao as Us,ap as Ut,aq as di,ar as xi,as as Za,at as er,au as hn,av as tr,aw as mi,ax as sr,ay as nr,az as ir,aA as ar,aB as ui,aC as rr,aD as hi,aE as cr,aF as lr,aG as or,aH as dr,aI as Rs,aJ as xr,aK as mr,aL as ur,aM as hr,aN as pr,aO as gr,aP as fr,aQ as br,aR as jr,aS as yr,aT as vr,aU as Nr,aV as wr,aW as zr,aX as Sr,aY as kr,aZ as Cr,a_ as Ar,a$ as $r,b0 as Qs,b1 as Pr,b2 as Lr,b3 as Dn,b4 as Dr,b5 as Tr,b6 as Ir,b7 as Rr,b8 as Er,b9 as Mr,ba as Or,bb as Fr,bc as Br,bd as qr,be as Gr,bf as _r,bg as Tn,bh as Ur,bi as Ks,bj as Qr,bk as In,bl as Rn,bm as Kr,bn as Hr,bo as Wr,bp as Vr,bq as Yr,br as Xr,bs as Jr,bt as Zr,bu as ec,bv as tc,bw as pi,bx as gi,by as sc,bz as fi,bA as nc,bB as bi,bC as ic,bD as ac,bE as js,bF as rc,bG as cc,bH as lc,bI as En}from"./index-wC-7udKS.js";import{R as oc}from"./RunRow-StjPY-W-.js";import{f as $t,C as et,a as Ge,b as jt,c as ot,d as Qe,e as Ue,g as bt,h as dc,i as Es,p as xc}from"./ChartPrimitives-Sl2xFVla.js";import{u as mc,t as uc,R as Ps,e as hc}from"./extract-error-message-Ccitgmu-.js";import{R as Pt,C as Lt,X as Dt,Y as Tt,T as It,L as ji,A as qt,a as Ms,b as pc,d as Os}from"./vendor-recharts-C9EZkgbP.js";import{C as yi,D as rs,a as gc,T as fc}from"./trash-2-CgxrJFpf.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const bc=[["path",{d:"M5 12h14",key:"1ays0h"}]],jc=Ts("minus",bc);const yc=[["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"}]],vc=Ts("scan-search",yc);const Nc=[["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"}]],wc=Ts("unplug",Nc);const zc=[["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"}]],Sc=Ts("upload",zc),kc=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function vi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Ni(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 wi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(vi).map(Ni).filter(Boolean)):new Set}function zi(t,s){const n=vi(t).map(Ni).filter(Boolean).filter(i=>!kc.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function Cc(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Ac(t,s){const n=wi(t);if(s.length<=1||n.size===0)return[...s];const i=new Set,a=[];for(const c of s){if(c.category!=="content"){a.push(c);continue}const l=zi(Cc(c),n);!l||i.has(l)||(i.add(l),a.push(c))}return a}function $c(t){const s=wi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const c=zi(a.query,s);return!c||i.has(c)?!1:(i.add(c),!0)})}function ks(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 Pc(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Hs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${ks(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${ks(t.prior)} ${s})`:`Flat ${n} (${ks(t.prior)} ${s})`}const Si=30;function Mn(t){return Math.round(t*10)/10}function Lc(t){return t.prior>=Si&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Mn(t.deltaAbs)} vs ${Mn(t.prior)}`}function Dc(t,s,n){return t.prior>=Si&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${ks(Math.round(t.deltaAbs))} ${s} ${n}`}function ln({state:t,label:s}){return e.jsx(ie,{tone:ta(t),children:s??ea(t)})}function On({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"}),c=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((l,p)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[l.citationState]??"bg-zinc-700"} ${l.model&&p>0&&n[p-1]?.model&&n[p-1].model!==l.model?"ring-1 ring-amber-300/80 ring-offset-1 ring-offset-zinc-950":""}`,title:[l.citationState,new Date(l.createdAt).toLocaleDateString(),l.model?`model ${l.model}`:null,l.model&&p>0&&n[p-1]?.model&&n[p-1].model!==l.model?"model changed":null].filter(Boolean).join(" — ")},p))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:c})]})}function on(t){const s=new Map;for(const i of t)for(const a of i.runHistory){const c=s.get(a.createdAt);c?c.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:c}])=>({runId:c,createdAt:i,citationState:a.includes("cited")?"cited":a.includes("emerging")?"emerging":"not-cited"}))}const Tc=320;function Fn(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 Bn(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 qn(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,c=t[t.length-2].citationState;if(c!=="cited"&&a==="cited")return`Newly ${n}`;if(c==="cited"&&a!=="cited")return"Lost since last run";let l=0;for(let p=t.length-1;p>=0&&t[p].citationState===a;p--)l++;return a==="cited"?l<=1?`${i} in latest run`:`${i} for ${l} runs`:l<=1?`Not ${n} in latest run`:`Not ${n} across ${l} runs`}function Ic(t,s){return t.map(n=>ki(n,s))}function ki(t,s){return s==="citations"?t:{...t,citationState:Fn(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Fn(n,s)}))}}function Gn(t,s){const n=s==="mentions"?"mention":"citation",i=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${i} pending`,tone:"pending"};const a=t[t.length-1].citationState,c=t.length>=2?t[t.length-2].citationState:null,l=a==="cited"||a==="emerging",p=c==="cited"||c==="emerging";return a==="lost"||c!==null&&p&&!l?{key:s,label:`Lost ${n}`,tone:"negative"}:a==="emerging"||c!==null&&!p&&l?{key:s,label:`New ${n}`,tone:"positive"}:c===null&&l?{key:s,label:`First ${n}`,tone:"positive"}:l?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Rc(t){const s=on(Ic(t,"mentions")),n=on(t);return[Gn(s,"mentions"),Gn(n,"citations")]}function Ec({signal:t}){const s=t.tone==="positive"?"border-emerald-500/25 bg-emerald-500/10 text-emerald-300":t.tone==="negative"?"border-rose-500/25 bg-rose-500/10 text-rose-300":t.tone==="pending"?"border-amber-500/20 bg-amber-500/10 text-amber-300":"border-zinc-700/60 bg-zinc-900/70 text-zinc-400";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function _n({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Rc(t).map(s=>e.jsx(Ec,{signal:s},s.key))})}function Mc({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=ci(),[a,c]=r.useState(new Set),[l,p]=r.useState("mentions"),[g,x]=r.useState(n),m=r.useMemo(()=>{const v=new Map;for(const k of t){const L=k.query,R=s?k.location??null:null,I=s?JSON.stringify([L,R]):L,N=v.get(I)??{key:I,phrase:L,location:R,items:[],rawItems:[]};N.items.push(ki(k,l)),N.rawItems.push(k),v.set(I,N)}return[...v.values()]},[t,l,s]),d=v=>{c(k=>{const L=new Set(k);return L.has(v)?L.delete(v):L.add(v),L})},$=l==="mentions"?"mentioned":"cited",b=l==="mentions"?"Mention History":"Citation History",C=l==="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":l==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="mentions"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":l==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="citations"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-zinc-500",children:l==="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:()=>{c(v=>v.size===m.length?new Set:new Set(m.map(k=>k.key)))},children:a.size===m.length&&m.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":g==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>x("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":g==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>x("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:b}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:m.map(({key:v,phrase:k,location:L,items:R,rawItems:I})=>{const N=a.has(v),j=R.map(T=>T.citationState),u=j.includes("cited")?"cited":j.includes("emerging")?"emerging":j.includes("lost")?"lost":j.every(T=>T==="pending")?"pending":"not-cited",E=on(R),_=R.filter(T=>T.citationState===sa.cited||T.citationState==="emerging").length,H=qn(E,l);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(v),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),d(v))},tabIndex:0,role:"button","aria-expanded":N,children:[e.jsx("td",{children:e.jsx(Is,{size:14,className:`transition-transform duration-150 text-zinc-500 ${N?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:k}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:L??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:R.map(T=>e.jsx(Ht,{provider:T.provider},T.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ln,{state:u,label:Bn(u,l)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${_} of ${R.length} engines ${C}`,children:[_,"/",R.length]})]})}),e.jsx("td",{children:e.jsx(On,{history:E})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:H}),e.jsx(_n,{items:I})]}),e.jsx("td",{})]}),N&&R.map((T,z)=>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(Ht,{provider:T.provider})}),e.jsx("td",{children:e.jsx(ln,{state:T.citationState,label:Bn(T.citationState,l)})}),e.jsx("td",{children:e.jsx(On,{history:T.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:qn(T.runHistory,l)}),e.jsx(_n,{items:[I[z]??T]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:M=>{M.stopPropagation(),i(T.id)},children:"View"})})]}),g==="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(Bc,{item:T,onViewFull:()=>i(T.id)})})]})]},T.id))]},v)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",$==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Oc(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const c=ia(a);return c.length>=4?[c]:[]}),...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 Fc(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 Bc({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}=Fc(t.answerSnippet,Tc),c=Oc(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:na(i,c)}),(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(l=>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:l},`c-${l}`)),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(l=>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:l},`co-${l}`)),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:l=>{l.stopPropagation(),s()},children:"View full answer →"})]})}function qc({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,c=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"}),c&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>{const p=i!=null&&i.toLowerCase()===l.domain.toLowerCase(),g=[a?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",p?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:g,onClick:a?()=>s(l.domain):void 0,title:a?`Filter answers to queries where ${l.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-zinc-100",children:l.domain}),e.jsx("td",{children:e.jsx(ie,{tone:aa(l.pressureLabel),children:l.pressureLabel})}),e.jsx("td",{className:"text-zinc-300 tabular-nums",children:l.totalQueries>0?`${l.citationCount} / ${l.totalQueries}`:"—"}),e.jsx("td",{className:"text-zinc-500 text-xs",children:l.citedQueries.length>0?l.citedQueries.join(", "):"Not cited"}),c&&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 ${l.domain}`,title:`Remove ${l.domain}`,onClick:x=>{x.stopPropagation(),n(l.domain)},children:"Remove"})})]},l.id)})})]})})}function Un({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:c,coverageValue:l,note:p,updatedAt:g,active:x,onClick:m}){return e.jsxs("button",{type:"button",onClick:m,className:`surface-card w-full text-left transition-colors ${x?"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(ie,{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:c})]}),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:l})]})]}),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:p}),e.jsx("span",{children:g?`Updated ${Je(g)}`:"No recent sync yet"})]})]})}function ys({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 Gc=6,Wt="__other__",Qt="_socialTotal";function _c(t,s=Gc){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const i=[...n.entries()].sort((m,d)=>d[1]!==m[1]?d[1]-m[1]:m[0].localeCompare(d[0])),a=i.slice(0,s),c=new Set(a.map(([m])=>m)),l=Math.max(0,i.length-s),p=new Map;for(const m of t){let d=p.get(m.date);d||(d={date:m.date,[Qt]:0},p.set(m.date,d));const $=c.has(m.source)?m.source:Wt;d[$]=(d[$]??0)+m.sessions,d[Qt]=(d[Qt]??0)+m.sessions}const g=[...p.values()].sort((m,d)=>String(m.date).localeCompare(String(d.date))),x=a.map(([m])=>m);return l>0&&x.push(Wt),{data:g,sources:x,otherCount:l}}function Kt(t){return t.replace(/\+/g," ")}function Ci(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Uc=["7d","30d","90d","all"],pt=Ue,dn=Qe.textDim,Ai=Qe.textFaint,ns=25,vs=50;function Ns(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function $i(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 Qc({projectName:t}){const{data:s,isLoading:n,isError:i}=mc(t);if(n)return e.jsx(W,{className:"p-5",children:e.jsx("div",{className:"text-sm text-zinc-500",children:"Loading server activity…"})});if(i)return e.jsx(W,{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(ft,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Manage sources →"})]})]})}),a.length===0?e.jsx(W,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-zinc-400",children:["No server traffic source connected yet."," ",e.jsx(ft,{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(W,{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(c=>e.jsxs("tr",{className:"border-t border-zinc-800/60",children:[e.jsx("td",{className:"px-4 py-3 text-zinc-100",children:c.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{tone:uc(c.status),children:c.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:c.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:c.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:c.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-zinc-400 text-xs",children:c.lastSyncedAt?$i(c.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(ft,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:c.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},c.id))})]})})]})}function Kc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Qc,{projectName:t}),e.jsx(Hc,{projectName:t})]})}function Hc({projectName:t}){const s=yt(),[n,i]=r.useState(null),[a,c]=r.useState(null),[l,p]=r.useState(!0),[g,x]=r.useState(!1),[m,d]=r.useState(!1),[$,b]=r.useState(null),[C,v]=r.useState(null),[k,L]=r.useState("sessions"),[R,I]=r.useState("desc"),[N,j]=r.useState("sessions"),[u,E]=r.useState("desc"),[_,H]=r.useState("sessions"),[T,z]=r.useState("desc"),[M,U]=r.useState("sessions"),[G,ne]=r.useState("desc"),[fe,xe]=r.useState(1),[pe,me]=r.useState([]),[he,je]=r.useState([]),[f,B]=r.useState([]),[te,ce]=r.useState(!1),[de,ke]=r.useState("30d");async function A(S){p(!0),b(null);try{const F=await s.fetchQuery({...ra({client:K,path:{name:t}}),staleTime:ss});if(S.current)return;if(i(F),!F.connected){c(null),me([]),je([]),B([]),p(!1);return}const Q=de==="all"?void 0:de,[Z,nt,Zt,we]=await Promise.all([s.fetchQuery({...ca({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).then(We=>We),s.fetchQuery({...la({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...oa({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...da({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[])]);if(S.current)return;c(Z),me(nt),je(Zt),B(we),p(!1)}catch(F){if(S.current)return;b(F instanceof Error?F.message:"Failed to load GA4 data"),p(!1)}}r.useEffect(()=>{const S={current:!1};return A(S),()=>{S.current=!0}},[t,de,s]);async function V(){x(!0),b(null),v(null);try{const S=await li(t);v(`Synced ${S.rowCount.toLocaleString()} page rows, ${S.aiReferralCount.toLocaleString()} AI and ${S.socialReferralCount.toLocaleString()} social referral rows (${S.days} days)`),await s.invalidateQueries({predicate:F=>{const Q=F.queryKey[0];return typeof Q?._id=="string"&&Q._id.startsWith("getApiV1ProjectsByNameGa")}}),await A({current:!1})}catch(S){b(S instanceof Error?S.message:"Sync failed")}finally{x(!1)}}async function Te(){d(!0),b(null),v(null);try{await xa(t),await s.invalidateQueries({predicate:S=>{const F=S.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),v("GA4 disconnected")}catch(S){b(S instanceof Error?S.message:"Disconnect failed")}finally{d(!1)}}function be(S){k===S?I(F=>F==="desc"?"asc":"desc"):(L(S),I("desc"))}function ye(S){N===S?E(F=>F==="desc"?"asc":"desc"):(j(S),E("desc"))}function X(S){_===S?z(F=>F==="desc"?"asc":"desc"):(H(S),z("desc"))}function O(S){xe(1),M===S?ne(F=>F==="desc"?"asc":"desc"):(U(S),ne("desc"))}const q=r.useMemo(()=>a?.topPages?[...a.topPages].sort((S,F)=>{const Q=S[k],Z=F[k];return typeof Q=="string"&&typeof Z=="string"?R==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):R==="asc"?Q-Z:Z-Q}):[],[a?.topPages,k,R]),ae=r.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((S,F)=>{const Q=S[N],Z=F[N];return typeof Q=="string"&&typeof Z=="string"?u==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):u==="asc"?Q-Z:Z-Q}):[],[a?.aiReferrals,N,u]),le=r.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((S,F)=>{const Q=S[M],Z=F[M];return typeof Q=="string"&&typeof Z=="string"?G==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):G==="asc"?Q-Z:Z-Q}):[],[a?.aiReferralLandingPages,M,G]),y=Math.max(1,Math.ceil(le.length/vs)),D=Math.min(Math.max(1,fe),y),Ce=(D-1)*vs,Oe=r.useMemo(()=>le.slice(Ce,Ce+vs),[le,Ce]),Ne=r.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((S,F)=>{const Q=S[_],Z=F[_];return typeof Q=="string"&&typeof Z=="string"?T==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):T==="asc"?Q-Z:Z-Q}):[],[a?.socialReferrals,_,T]),{socialChartData:vt,socialChartSources:dt,socialOtherCount:Ke}=r.useMemo(()=>{const S=_c(f);return{socialChartData:S.data,socialChartSources:S.sources,socialOtherCount:S.otherCount}},[f]),{chartData:Nt,chartSources:Fe,dateRange:tt}=r.useMemo(()=>{const S=[...new Set(pe.map(we=>we.source))],F=new Map;for(const we of he)F.set(we.date,{_totalSessions:we.sessions,_organicSessions:we.organicSessions});const Q=new Map;for(const we of pe){const We=`${we.date}::${we.source}`,Et=Q.get(We)??0;Q.set(We,Math.max(Et,we.sessions))}for(const[we,We]of Q){const[Et,xt]=we.split("::");let it=F.get(Et);it||(it={_totalSessions:0,_organicSessions:0},F.set(Et,it)),it[xt]=(it[xt]??0)+We}const Z=[...F.entries()].sort(([we],[We])=>we.localeCompare(We)).map(([we,We])=>({date:we,...We})),nt=Z.map(we=>we.date),Zt=nt.length>0?{start:nt[0],end:nt[nt.length-1]}:null;return{chartData:Z,chartSources:S,dateRange:Zt}},[pe,he]);if(l&&!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(Wc,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:S=>{const F=S.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),await A({current:!1})))()}});const st=a?.organicSharePctDisplay??"0%",Rt=a?.channelBreakdown?.organic.sharePctDisplay??st,wt=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,Vt=a?.aiSessionsDeduped??0,Ae=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,Yt=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",_e=a?new Set(a.aiReferrals.map(S=>S.source.toLowerCase())).size:0,Ee=ae[0]??null,zt=a?.totalDirectSessions??0,Xt=a?.directSharePctDisplay??"0%",Jt=a?.channelBreakdown?.direct.sessions??zt,xs=a?.channelBreakdown?.direct.sharePctDisplay??Xt,at=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,Ie=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",h=a?.socialSessions??0,Y=a?.socialSharePctDisplay??"0%",se=a?.channelBreakdown?.social.sessions??h,Pe=a?.channelBreakdown?.social.sharePctDisplay??Y,ve=a?new Set(a.socialReferrals.map(S=>S.source.toLowerCase())).size:0,He=Ne[0]??null;return e.jsxs(e.Fragment,{children:[$&&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:$}),C&&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:C}),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(P,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ps,{className:`w-3.5 h-3.5 mr-1.5 ${g?"animate-spin":""}`}),g?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:m,onClick:ee(Te),children:[e.jsx(wc,{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(Se,{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(S=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${de===S?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>ke(S),children:S==="all"?"All":S},S))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ws,{value:Ns(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ws,{value:Ns(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${st} of total`,tone:"positive"}),e.jsx(Ws,{value:Ns(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(P,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ps,{className:`w-3.5 h-3.5 mr-1.5 ${g?"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(Se,{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."})]})]}),tt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(tt.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(tt.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Nt.length>0&&e.jsxs(W,{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:Fe.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Fe.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Fe.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(Pt,{width:"100%",height:"100%",children:e.jsxs(Lt,{data:Nt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:Ge,tickLine:!1,axisLine:{stroke:et},tickFormatter:$t}),e.jsx(Tt,{tick:Ge,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ot,labelFormatter:jt,formatter:(S,F)=>{const Q=typeof S=="number"?S.toLocaleString():String(S??0),Z=String(F??"");return Z==="_totalSessions"?[Q,"Total Sessions"]:Z==="_organicSessions"?[Q,"Organic Sessions"]:[Q,Z]}}),e.jsx(ji,{wrapperStyle:{fontSize:11,color:Qe.text},formatter:S=>S==="_totalSessions"?"Total Sessions":S==="_organicSessions"?"Organic Sessions":S}),e.jsx(qt,{type:"monotone",dataKey:"_totalSessions",stroke:Qe.textFaint,fill:Qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Fe.map((S,F)=>e.jsx(qt,{type:"monotone",dataKey:S,stackId:"ai",stroke:pt[F%pt.length],fill:pt[F%pt.length],fillOpacity:.4,strokeWidth:1.5},S))]})})})]}),e.jsxs(W,{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(Ze,{label:"Organic",value:Rt,hint:`${wt.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(Ze,{label:"Social",value:Pe,hint:`${se.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(Ze,{label:"Direct",value:xs,hint:`${Jt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(Ze,{label:"Known AI referrers (lower bound)",value:Yt,hint:`${Ae.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(Ze,{label:"Other channels",value:Ie,hint:`${at.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."})]}),Ee&&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:Ee.source})," via ",Ee.medium,", accounting for ",Ee.sessions.toLocaleString()," sessions."]})]}),e.jsxs(W,{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?`${_e} 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(Me,{label:"Source",sortKey:"source",current:N,dir:u,onSort:ye,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:N,dir:u,onSort:ye,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:N,dir:u,onSort:ye,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:N,dir:u,onSort:ye,align:"right"})]})}),e.jsx("tbody",{children:ae.map(S=>e.jsx(Yc,{referral:S,totalSessions:Vt},`${S.source}:${S.medium}:${S.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(W,{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:le.length>vs?`${Ce+1}–${Ce+Oe.length} of ${le.length} rows`:le.length>0?`${le.length} rows`:"No landing-page rows"})]}),le.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(Me,{label:"Landing Page",sortKey:"landingPage",current:M,dir:G,onSort:O,align:"left"}),e.jsx(Me,{label:"Source",sortKey:"source",current:M,dir:G,onSort:O,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:M,dir:G,onSort:O,align:"right"}),e.jsx(Me,{label:"Users",sortKey:"users",current:M,dir:G,onSort:O,align:"right"})]})}),e.jsx("tbody",{children:Oe.map(S=>e.jsx(Xc,{row:S},`${S.landingPage}:${S.source}:${S.medium}:${S.sourceDimension}`))})]})}),y>1&&e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>xe(D-1),disabled:D<=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 ",D," of ",y]}),e.jsx("button",{type:"button",onClick:()=>xe(D+1),disabled:D>=y,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(Se,{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."})]})]}),vt.length>0&&e.jsxs(W,{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"})]}),Ke>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",dt.length-1," sources · ",Ke," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Lt,{data:vt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:Ge,tickLine:!1,axisLine:{stroke:et},tickFormatter:$t}),e.jsx(Tt,{tick:Ge,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ot,labelFormatter:jt,formatter:(S,F)=>{const Q=typeof S=="number"?S.toLocaleString():String(S??0),Z=String(F??"");if(Z===Qt)return[Q,"Total Social"];if(Z===Wt){const nt=`Other (${Ke} source${Ke===1?"":"s"})`;return[Q,nt]}return[Q,Kt(Z)]}}),e.jsx(qt,{type:"monotone",dataKey:Qt,stroke:Ai,fill:Qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),dt.map((S,F)=>{const Z=S===Wt?dn:pt[F%pt.length];return e.jsx(qt,{type:"monotone",dataKey:S,stackId:"social",stroke:Z,fill:Z,fillOpacity:.4,strokeWidth:1.5},S)})]})})}),e.jsx(Zc,{sources:dt,otherCount:Ke})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(W,{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(Ze,{label:"Social Sessions",value:Ns(h),hint:`${h.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Ze,{label:"Share of Traffic",value:Y,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Ze,{label:"Platforms",value:String(ve),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."})]}),He&&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:`${He.source} via ${He.medium}`,children:Ci(Kt(He.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:He.medium,children:["via ",Kt(He.medium)," · ",He.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(Ze,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Ze,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Ze,{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(W,{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?Ne.length>ns&&!te?`Top ${ns} of ${Ne.length}`:`${Ne.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(Me,{label:"Source",sortKey:"source",current:_,dir:T,onSort:X,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:_,dir:T,onSort:X,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:_,dir:T,onSort:X,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:_,dir:T,onSort:X,align:"right"})]})}),e.jsx("tbody",{children:(te?Ne:Ne.slice(0,ns)).map(S=>e.jsx(Jc,{referral:S,totalSessions:h},`${S.source}:${S.medium}:${S.channelGroup}`))})]})}),Ne.length>ns&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ce(S=>!S),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:te?`Show top ${ns}`:`Show all ${Ne.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(Se,{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(Me,{label:"Landing Page",sortKey:"landingPage",current:k,dir:R,onSort:be,align:"left"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:k,dir:R,onSort:be,align:"right"}),e.jsx(Me,{label:"Organic",sortKey:"organicSessions",current:k,dir:R,onSort:be,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Me,{label:"Users",sortKey:"users",current:k,dir:R,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:q.map(S=>e.jsx(Vc,{page:S},S.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 ${$i(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function Wc({projectName:t,onConnected:s}){const[n,i]=r.useState(""),[a,c]=r.useState(null),[l,p]=r.useState(null),[g,x]=r.useState(!1),[m,d]=r.useState(null),$=r.useRef(null),b=r.useCallback(v=>{const k=v.target.files?.[0];if(!k)return;d(null),c(k.name);const L=new FileReader;L.onload=()=>{const R=L.result;try{const I=JSON.parse(R);if(!I.client_email||!I.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)."),p(null);return}p(R)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),p(null)}},L.onerror=()=>{d("Failed to read file."),p(null)},L.readAsText(k)},[]);async function C(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!l){d("Please upload a service account key file.");return}x(!0);try{await ma(t,{propertyId:n.trim(),keyJson:l});try{await li(t)}catch{}s()}catch(v){d(v instanceof Error?v.message:"Failed to connect GA4")}finally{x(!1)}}return e.jsxs(W,{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."}),m&&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:m}),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:v=>i(v.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:$,type:"file",accept:".json,application/json",onChange:b,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>$.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(Sc,{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(P,{variant:"default",size:"sm",disabled:g||!n.trim()||!l,onClick:ee(C),children:g?"Connecting & syncing…":"Connect GA4"})]})}function Me({label:t,sortKey:s,current:n,dir:i,onSort:a,align:c}){const l=n===s;return e.jsx("th",{className:`py-1 ${c==="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}${l?` (currently ${i==="asc"?"ascending":"descending"})`:""}`,children:[t,l&&e.jsx("span",{className:"ml-0.5",children:i==="asc"?"↑":"↓"})]})})}const Pi={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function Ws({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 ${Pi[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Ze({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(Se,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Pi[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Vc({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 Li={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Di={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 Yc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=Li[t.sourceDimension]??t.sourceDimension,a=Di[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 Xc({row:t}){const s=Li[t.sourceDimension]??t.sourceDimension,n=Di[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 Jc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Kt(t.source),c=Kt(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:c}),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 Zc({sources:t,otherCount:s}){const n=[{key:Qt,color:Ai,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===Wt)n.push({key:Wt,color:dn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const c=Kt(a);n.push({key:a,color:pt[i%pt.length]??dn,label:Ci(c,32),tooltip:c})}}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 el(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 tl=["7d","30d","90d","all"],ws=500,ut=25;function sl({projectName:t,refreshNonce:s}){const n=yt(),[i,a]=r.useState(!1),[c,l]=r.useState([]),[p,g]=r.useState([]),[x,m]=r.useState([]),[d,$]=r.useState(null),[b,C]=r.useState([]),[v,k]=r.useState([]),[L,R]=r.useState(null),[I,N]=r.useState(""),[j,u]=r.useState(""),[E,_]=r.useState("30"),[H,T]=r.useState(!1),[z,M]=r.useState("30d"),[U,G]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[ne,fe]=r.useState(0),[xe,pe]=r.useState(!1),[me,he]=r.useState(0),[je,f]=r.useState(!1),[B,te]=r.useState(""),[ce,de]=r.useState(!0),[ke,A]=r.useState(!1),[V,Te]=r.useState(!1),[be,ye]=r.useState(!1),[X,O]=r.useState(!1),[q,ae]=r.useState(!1),[le,y]=r.useState(!1),[D,Ce]=r.useState(null),[Oe,Ne]=r.useState(!1),[vt,dt]=r.useState(!1),[Ke,Nt]=r.useState(null),[Fe,tt]=r.useState(""),[st,Rt]=r.useState(!1),[wt,Vt]=r.useState(!1),[Ae,Yt]=r.useState("indexed"),[_e,Ee]=r.useState(null),zt=!!(U.query.trim()||U.page.trim()||_e),Xt=_e!==null,Jt=r.useMemo(()=>{if(!_e)return x;const{key:o,dir:w}=_e;return[...x].sort((J,oe)=>{const Le=o===At.CTR?Number.isFinite(J.ctr)?J.ctr:0:J[o],qe=o===At.CTR?Number.isFinite(oe.ctr)?oe.ctr:0:oe[o];return w==="asc"?Le-qe:qe-Le})},[x,_e]),[xs,at]=r.useState([]),[Ie,h]=r.useState(null),[Y,se]=r.useState(1);r.useEffect(()=>{se(1)},[D,Ae,Ie]);const Pe=r.useMemo(()=>Ie?(D?.reasonGroups??[]).find(o=>o.reason===Ie):void 0,[D,Ie]),ve=r.useMemo(()=>D?Ae==="indexed"?D.indexed:Ae==="deindexed"?D.deindexed:Ae==="notIndexed"?Ie?Pe?.urls??[]:(D.reasonGroups??[]).length===0?D.notIndexed:[]:[]:[],[D,Ae,Ie,Pe]),He=Math.max(1,Math.ceil(ve.length/ut)),S=Math.min(Math.max(1,Y),He),F=(S-1)*ut,Q=ve.length>ut,Z=ve.length===0?0:F+1,nt=Math.min(F+ut,ve.length),Zt=r.useMemo(()=>D?.indexed.slice(F,F+ut)??[],[D,F]),we=r.useMemo(()=>D?.notIndexed.slice(F,F+ut)??[],[D,F]),We=r.useMemo(()=>D?.deindexed.slice(F,F+ut)??[],[D,F]),Et=r.useMemo(()=>(Pe?.urls??[]).slice(F,F+ut),[Pe,F]),[xt,it]=r.useState(!1),[jn,ue]=r.useState(null),[rt,ms]=r.useState(null),[yn,ct]=r.useState(null);function Fi(o,w){const J=hc(o),oe=el(J);oe?(ms(oe),ue(null)):(ms(null),ue(J.message||w))}const ze=c.find(o=>o.connectionType==="gsc"),Bi=x.length>0||b.length>0||v.length>0,qs=ua(),es=ha(),Gs=pa();async function vn(o){if(!o){g([]),N("");return}Te(!0);try{const{sites:w}=await n.fetchQuery({...Ca({client:K,path:{name:t}}),staleTime:Re});g(w),N(o.propertyId??w[0]?.siteUrl??""),ms(null)}catch(w){g([]),Fi(w,"Failed to load Search Console properties")}finally{Te(!1)}}async function Mt(o){O(!0);const w=o??ne;try{const J=parseInt(U.limit,10)||20,oe=zt?ws:J+1,Le=zt?0:w,qe={limit:String(oe)};U.startDate&&(qe.startDate=U.startDate),U.endDate&&(qe.endDate=U.endDate),U.query&&(qe.query=U.query),U.page&&(qe.page=U.page),Le>0&&(qe.offset=String(Le)),z&&z!=="all"&&!U.startDate&&(qe.window=z);const Ve=await n.fetchQuery({...ba({client:K,path:{name:t},query:qe}),staleTime:Re});zt?(pe(!1),m(Ve),he(Ve.length),f(!0)):(pe(Ve.length>J),m(Ve.slice(0,J)),he(0),f(!1))}catch(J){m([]),pe(!1),he(0),ue(J instanceof Error?J.message:"Failed to load GSC performance data")}finally{O(!1)}}async function _s(){try{const o={};U.startDate&&(o.startDate=U.startDate),U.endDate&&(o.endDate=U.endDate),z&&z!=="all"&&!U.startDate&&(o.window=z);const w=await n.fetchQuery({...ja({client:K,path:{name:t},query:o}),staleTime:Re});$(w)}catch{$(null)}}async function us(){ae(!0);try{const o=B.trim()||void 0,w={limit:"20"};o&&(w.url=o);const[J,oe]=await Promise.all([n.fetchQuery({...Sa({client:K,path:{name:t},query:w}),staleTime:Re}),n.fetchQuery({...ka({client:K,path:{name:t}}),staleTime:Re})]);C(J),k(oe)}catch(o){C([]),k([]),ue(o instanceof Error?o.message:"Failed to load GSC inspection history")}finally{ae(!1)}}async function Nn(){Ne(!0);try{const[o,w]=await Promise.all([n.fetchQuery({...oi({client:K,path:{name:t}}),staleTime:Re}),n.fetchQuery({...wa({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);Ce(o),at(w)}catch(o){Ce(null),at([]),ue(o instanceof Error?o.message:"Failed to load coverage data")}finally{Ne(!1)}}async function wn(o){it(!0),ue(null);try{const w=await Pn(t,{urls:o}),{succeeded:J,failed:oe,total:Le}=w.summary;re({title:"Indexing requested",detail:oe===0?`${J} URL${J!==1?"s":""} submitted for indexing.`:`${J}/${Le} submitted successfully, ${oe} failed.`,tone:oe===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(w){ue(w instanceof Error?w.message:"Failed to request indexing")}finally{it(!1)}}async function qi(){it(!0),ue(null);try{const o=await Pn(t,{urls:[],allUnindexed:!0}),{succeeded:w,failed:J,total:oe}=o.summary;re({title:"Indexing requested",detail:J===0?`${w} unindexed URL${w!==1?"s":""} submitted for indexing.`:`${w}/${oe} submitted successfully, ${J} failed.`,tone:J===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(o){ue(o instanceof Error?o.message:"Failed to request indexing")}finally{it(!1)}}async function hs(){if(Fe.trim()){Rt(!0),ue(null);try{await Na(t,"gsc",Fe.trim()),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(o=>o.map(w=>w.connectionType==="gsc"?{...w,sitemapUrl:Fe.trim()}:w)),re({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),tt("")}catch(o){ue(o instanceof Error?o.message:"Failed to save sitemap URL")}finally{Rt(!1)}}}async function zn(){ue(null);try{const o=await es.mutateAsync({projectName:t,projectLabel:t});Nt(o.sitemaps),l(w=>w.map(J=>J.connectionType==="gsc"?{...J,sitemapUrl:o.primarySitemapUrl}:J))}catch{}}async function Gi(){dt(!0),ue(null);try{const o=await $a(t);n.setQueryData(Pa({client:K,path:{name:t}}),o),Nt(o.sitemaps),o.sitemaps.length===0&&ct("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(o){ue(o instanceof Error?o.message:"Failed to list sitemaps")}finally{dt(!1)}}async function Sn(){de(!0),ue(null);try{const[o,w]=await Promise.all([fa().catch(()=>null),n.fetchQuery({...un({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);a(!!o?.google?.configured),l(w);const J=w.find(oe=>oe.connectionType==="gsc");await Promise.all([vn(J),Mt(),_s(),us(),Nn()])}finally{de(!1)}}r.useEffect(()=>{Sn()},[t,s]),r.useEffect(()=>{fe(0),Mt(0),_s()},[z]);const kn=r.useRef(!1);r.useEffect(()=>{if(!kn.current){kn.current=!0;return}fe(0),Mt(0)},[Xt]);async function _i(){if(!i){ue("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}A(!0),ue(null),ct(null);try{const{authUrl:o}=await va(t,"gsc");if(!o.startsWith("https://accounts.google.com/")){ue("Unexpected OAuth redirect URL. Please try again.");return}const w=window.open(o,"_blank","width=600,height=700");if(!w){window.location.assign(o);return}ct("Finish the Google consent flow in the popup, then close it to refresh this project.");const J=window.setInterval(()=>{w.closed&&(window.clearInterval(J),ct(null),n.invalidateQueries({predicate:oe=>{const Le=oe.queryKey[0];return typeof Le?._id=="string"&&Le._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),Sn())},1e3)}catch(o){ue(o instanceof Error?o.message:"Failed to start OAuth flow")}finally{A(!1)}}async function Ui(){ue(null),ct(null);try{await ya(t,"gsc"),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(o=>o.filter(w=>w.connectionType!=="gsc")),g([]),N("")}catch(o){ue(o instanceof Error?o.message:"Failed to disconnect")}}async function Qi(){if(I){ye(!0),ue(null);try{await Aa(t,"gsc",I),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(o=>o.map(w=>w.connectionType==="gsc"?{...w,propertyId:I}:w)),re({title:"GSC property updated",detail:`${t} is now linked to ${I}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(o){ue(o instanceof Error?o.message:"Failed to save GSC property")}finally{ye(!1)}}}async function Ki(){ue(null),ct(null);try{await qs.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(E,10)||void 0,full:H||void 0}}),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function Cn(){if(j.trim()){y(!0),ue(null),ct(null);try{const o=await za(t,j.trim());await n.invalidateQueries({predicate:w=>{const J=w.queryKey[0];return typeof J?._id=="string"&&J._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),R(o),u(""),await us()}catch(o){ue(o instanceof Error?o.message:"Failed to inspect URL")}finally{y(!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"})]})}),rt&&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:rt.title}),e.jsx("p",{className:"mt-0.5 text-amber-200/90",children:rt.message}),(Bt(rt.enableUrl)||Bt(rt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Bt(rt.enableUrl)&&e.jsx("a",{href:Bt(rt.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 ↗"}),Bt(rt.indexingApiUrl)&&e.jsx("a",{href:Bt(rt.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:()=>ms(null),children:"×"})]})}),jn&&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:[jn,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>ue(null),children:"×"})]}),yn&&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:[yn,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>ct(null),children:"×"})]}),ce?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[ze?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:ze.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Je(ze.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:ee(Ui),children:"Disconnect"})]}):e.jsxs(W,{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(ie,{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(P,{type:"button",variant:"outline",size:"sm",disabled:ke,onClick:ee(_i),children:ke?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ft,{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."})]})]})]}),ze&&!ze.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(P,{type:"button",size:"sm",disabled:es.isPending||!ze.propertyId,onClick:ee(zn),children:es.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:Fe,onChange:o=>tt(o.target.value),onKeyDown:o=>o.key==="Enter"&&void hs()}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:st||!Fe.trim(),onClick:ee(hs),children:st?"Saving…":"Save sitemap URL"})]})]})]})]})}),(ze||Bi)&&e.jsxs(e.Fragment,{children:[e.jsxs(W,{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:[D&&D.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{qi()},children:xt?"Requesting…":`Request indexing (${D.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Oe,onClick:()=>{Nn()},children:Oe?"Loading…":"Refresh coverage"})]})]}),D&&D.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const o=D.summary.indexed+D.summary.notIndexed,w=o>0?D.summary.indexed/o:0,J=o>0?D.summary.notIndexed/o:0,oe=54,Le=2*Math.PI*oe,qe=Le*(1-w),Ve=Le*J,Ot=Le*w;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:oe,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:oe,fill:"none",stroke:bt.positiveDeep,strokeWidth:"14",strokeDasharray:Le,strokeDashoffset:qe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),D.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:oe,fill:"none",stroke:Qe.textFaint,strokeWidth:"14",strokeDasharray:`${Ve} ${Le-Ve}`,strokeDashoffset:-Ot,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:[(w*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:D.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:D.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:["Not indexed",(D.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-zinc-600",children:["· ",(D.reasonGroups??[]).length," ",(D.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),D.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:D.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(o=>{const w=o==="indexed"?D.indexed.length:o==="notIndexed"?D.notIndexed.length:D.deindexed.length,J=o==="indexed"?"Indexed":o==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${Ae===o?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{Yt(o),h(null)},children:[J," (",w,")"]},o)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ae==="indexed"&&D.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:Zt.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-400",children:o.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:o.crawlTime?o.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:o.isMobileFriendly===!0?"Yes":o.isMobileFriendly===!1?"No":"—"})]},o.id))})]}),Ae==="notIndexed"&&!Ie&&(D.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:(D.reasonGroups??[]).map(o=>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:()=>h(o.reason),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),h(o.reason))},tabIndex:0,role:"button","aria-label":`View ${o.reason} pages`,children:[e.jsx("td",{className:"text-zinc-200",children:o.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:o.count})]},o.reason))})]}),Ae==="notIndexed"&&!Ie&&(D.reasonGroups??[]).length===0&&D.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:we.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-400",children:o.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:o.coverageState??"Unknown"})]},o.id))})]}),Ae==="notIndexed"&&Ie&&(()=>{const o=(D.reasonGroups??[]).find(w=>w.reason===Ie);return o?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:()=>h(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:o.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[o.count," affected page",o.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{wn(o.urls.map(w=>w.url))},children:xt?"Requesting…":`Request indexing (${o.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:Et.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:w.url}),e.jsx("td",{className:"text-zinc-400",children:w.crawlTime?w.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:()=>{wn([w.url])},title:"Request indexing",children:"Index"})})]},w.id))})]})]}):null})(),Ae==="deindexed"&&D.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:We.map((o,w)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-400",children:o.previousState}),e.jsx("td",{className:"text-zinc-400",children:o.currentState}),e.jsx("td",{className:"text-zinc-400",children:o.transitionDate.split("T")[0]})]},`${o.url}-${w}`))})]}),(Ae==="indexed"&&D.indexed.length===0||Ae==="notIndexed"&&!Ie&&D.notIndexed.length===0||Ae==="deindexed"&&D.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:Z.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-zinc-300",children:nt.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-zinc-300",children:ve.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>se(o=>Math.max(1,o-1)),disabled:S<=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(dc,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-zinc-200",children:S})," of"," ",e.jsx("span",{className:"text-zinc-200",children:He})]}),e.jsxs("button",{type:"button",onClick:()=>se(o=>Math.min(He,o+1)),disabled:S>=He,"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(Is,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:Oe?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(W,{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:tl.map(o=>e.jsx("button",{type:"button",role:"tab","aria-selected":z===o,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${z===o?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>M(o),children:o==="all"?"All":o},o))}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:X,onClick:()=>{fe(0),Mt(0),_s()},children:X?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const o=d.daily,w=Math.max(...o.map(ge=>ge.impressions),1),{clicks:J,impressions:oe,ctr:Le}=d.totals,qe=(Le*100).toFixed(1),Ve=700,Ot=220,Ye={top:12,bottom:36,left:48,right:12},Hi=Ve-Ye.left-Ye.right,Ft=Ot-Ye.top-Ye.bottom,ts=Hi/o.length,ps=Math.max(Math.min(ts*.35,24),4),An=Math.max(ps*.15,1),Wi=ge=>{if(ge<=0)return 1;const lt=Math.pow(10,Math.floor(Math.log10(ge))),Xe=ge/lt,mt=Xe<=1.5?1.5:Xe<=3?3:Xe<=5?5:10;return Math.ceil(mt*lt)},gs=4,fs=Math.ceil(Wi(w)/gs)*gs,Vi=Array.from({length:gs+1},(ge,lt)=>fs/gs*lt),Yi=ge=>ge>=1e3?`${(ge/1e3).toFixed(ge>=1e4?0:1)}k`:String(ge);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:J.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:oe.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[qe,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ve} / ${Ot}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ve} ${Ot}`,className:"h-full w-full",children:[Vi.map((ge,lt)=>{const Xe=Ye.top+Ft-ge/fs*Ft;return e.jsxs("g",{children:[e.jsx("line",{x1:Ye.left,y1:Xe,x2:Ve-Ye.right,y2:Xe,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:Ye.left-6,y:Xe+3.5,textAnchor:"end",fill:Qe.text,fontSize:"10",fontFamily:"inherit",children:Yi(ge)})]},`t-${lt}`)}),o.map((ge,lt)=>{const Xe=Ye.left+ts*lt+ts/2,mt=ge.impressions/fs*Ft,bs=ge.clicks/fs*Ft;return e.jsxs("g",{children:[e.jsx("title",{children:`${ge.date}
1
+ import{j as e,r,L as ft,n as yt,u as $e,o as ls,A as Xi,B as Ji,h as Zi}from"./vendor-tanstack-Be8JdV5M.js";import{c as Ts,T as ie,t as ea,a as ta,u as ci,C as sa,b as Is,P as Ht,B as P,h as na,d as ia,e as aa,f as Je,g as W,i as ee,I as Se,j as ss,k as ra,l as K,m as ca,n as la,o as oa,p as da,q as li,r as xa,s as ma,S as At,v as ua,w as ha,x as pa,y as Bt,z as ga,A as $n,D as fa,G as Re,E as un,F as ba,H as ja,J as ya,K as va,L as Na,M as re,N as Pn,O as oi,Q as wa,R as za,U as Sa,V as ka,W as Ca,X as Aa,Y as $a,Z as Pa,_ as La,$ as Da,a0 as Ta,a1 as Ia,a2 as Ra,a3 as Ea,a4 as Ma,a5 as Oa,a6 as os,a7 as Fa,a8 as Ba,a9 as Ln,aa as qa,ab as Ga,ac as _a,ad as Ua,ae as $s,af as Qa,ag as Ka,ah as Ha,ai as Wa,aj as cn,ak as Va,al as Ya,am as Xa,an as Ja,ao as Us,ap as Ut,aq as di,ar as xi,as as Za,at as er,au as hn,av as tr,aw as mi,ax as sr,ay as nr,az as ir,aA as ar,aB as ui,aC as rr,aD as hi,aE as cr,aF as lr,aG as or,aH as dr,aI as Rs,aJ as xr,aK as mr,aL as ur,aM as hr,aN as pr,aO as gr,aP as fr,aQ as br,aR as jr,aS as yr,aT as vr,aU as Nr,aV as wr,aW as zr,aX as Sr,aY as kr,aZ as Cr,a_ as Ar,a$ as $r,b0 as Qs,b1 as Pr,b2 as Lr,b3 as Dn,b4 as Dr,b5 as Tr,b6 as Ir,b7 as Rr,b8 as Er,b9 as Mr,ba as Or,bb as Fr,bc as Br,bd as qr,be as Gr,bf as _r,bg as Tn,bh as Ur,bi as Ks,bj as Qr,bk as In,bl as Rn,bm as Kr,bn as Hr,bo as Wr,bp as Vr,bq as Yr,br as Xr,bs as Jr,bt as Zr,bu as ec,bv as tc,bw as pi,bx as gi,by as sc,bz as fi,bA as nc,bB as bi,bC as ic,bD as ac,bE as js,bF as rc,bG as cc,bH as lc,bI as En}from"./index-Dr2rxkFR.js";import{R as oc}from"./RunRow-CZ1bXteZ.js";import{f as $t,C as et,a as Ge,b as jt,c as ot,d as Qe,e as Ue,g as bt,h as dc,i as Es,p as xc}from"./ChartPrimitives-BnYX5sRb.js";import{u as mc,t as uc,R as Ps,e as hc}from"./extract-error-message-DoIzPHJI.js";import{R as Pt,C as Lt,X as Dt,Y as Tt,T as It,L as ji,A as qt,a as Ms,b as pc,d as Os}from"./vendor-recharts-C9EZkgbP.js";import{C as yi,D as rs,a as gc,T as fc}from"./trash-2-C9Ebw5p4.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const bc=[["path",{d:"M5 12h14",key:"1ays0h"}]],jc=Ts("minus",bc);const yc=[["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"}]],vc=Ts("scan-search",yc);const Nc=[["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"}]],wc=Ts("unplug",Nc);const zc=[["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"}]],Sc=Ts("upload",zc),kc=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function vi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Ni(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 wi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(vi).map(Ni).filter(Boolean)):new Set}function zi(t,s){const n=vi(t).map(Ni).filter(Boolean).filter(i=>!kc.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function Cc(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Ac(t,s){const n=wi(t);if(s.length<=1||n.size===0)return[...s];const i=new Set,a=[];for(const c of s){if(c.category!=="content"){a.push(c);continue}const l=zi(Cc(c),n);!l||i.has(l)||(i.add(l),a.push(c))}return a}function $c(t){const s=wi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const c=zi(a.query,s);return!c||i.has(c)?!1:(i.add(c),!0)})}function ks(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 Pc(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Hs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${ks(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${ks(t.prior)} ${s})`:`Flat ${n} (${ks(t.prior)} ${s})`}const Si=30;function Mn(t){return Math.round(t*10)/10}function Lc(t){return t.prior>=Si&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Mn(t.deltaAbs)} vs ${Mn(t.prior)}`}function Dc(t,s,n){return t.prior>=Si&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${ks(Math.round(t.deltaAbs))} ${s} ${n}`}function ln({state:t,label:s}){return e.jsx(ie,{tone:ta(t),children:s??ea(t)})}function On({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"}),c=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((l,p)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[l.citationState]??"bg-zinc-700"} ${l.model&&p>0&&n[p-1]?.model&&n[p-1].model!==l.model?"ring-1 ring-amber-300/80 ring-offset-1 ring-offset-zinc-950":""}`,title:[l.citationState,new Date(l.createdAt).toLocaleDateString(),l.model?`model ${l.model}`:null,l.model&&p>0&&n[p-1]?.model&&n[p-1].model!==l.model?"model changed":null].filter(Boolean).join(" — ")},p))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:c})]})}function on(t){const s=new Map;for(const i of t)for(const a of i.runHistory){const c=s.get(a.createdAt);c?c.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:c}])=>({runId:c,createdAt:i,citationState:a.includes("cited")?"cited":a.includes("emerging")?"emerging":"not-cited"}))}const Tc=320;function Fn(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 Bn(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 qn(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,c=t[t.length-2].citationState;if(c!=="cited"&&a==="cited")return`Newly ${n}`;if(c==="cited"&&a!=="cited")return"Lost since last run";let l=0;for(let p=t.length-1;p>=0&&t[p].citationState===a;p--)l++;return a==="cited"?l<=1?`${i} in latest run`:`${i} for ${l} runs`:l<=1?`Not ${n} in latest run`:`Not ${n} across ${l} runs`}function Ic(t,s){return t.map(n=>ki(n,s))}function ki(t,s){return s==="citations"?t:{...t,citationState:Fn(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Fn(n,s)}))}}function Gn(t,s){const n=s==="mentions"?"mention":"citation",i=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${i} pending`,tone:"pending"};const a=t[t.length-1].citationState,c=t.length>=2?t[t.length-2].citationState:null,l=a==="cited"||a==="emerging",p=c==="cited"||c==="emerging";return a==="lost"||c!==null&&p&&!l?{key:s,label:`Lost ${n}`,tone:"negative"}:a==="emerging"||c!==null&&!p&&l?{key:s,label:`New ${n}`,tone:"positive"}:c===null&&l?{key:s,label:`First ${n}`,tone:"positive"}:l?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Rc(t){const s=on(Ic(t,"mentions")),n=on(t);return[Gn(s,"mentions"),Gn(n,"citations")]}function Ec({signal:t}){const s=t.tone==="positive"?"border-emerald-500/25 bg-emerald-500/10 text-emerald-300":t.tone==="negative"?"border-rose-500/25 bg-rose-500/10 text-rose-300":t.tone==="pending"?"border-amber-500/20 bg-amber-500/10 text-amber-300":"border-zinc-700/60 bg-zinc-900/70 text-zinc-400";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function _n({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Rc(t).map(s=>e.jsx(Ec,{signal:s},s.key))})}function Mc({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=ci(),[a,c]=r.useState(new Set),[l,p]=r.useState("mentions"),[g,x]=r.useState(n),m=r.useMemo(()=>{const v=new Map;for(const k of t){const L=k.query,R=s?k.location??null:null,I=s?JSON.stringify([L,R]):L,N=v.get(I)??{key:I,phrase:L,location:R,items:[],rawItems:[]};N.items.push(ki(k,l)),N.rawItems.push(k),v.set(I,N)}return[...v.values()]},[t,l,s]),d=v=>{c(k=>{const L=new Set(k);return L.has(v)?L.delete(v):L.add(v),L})},$=l==="mentions"?"mentioned":"cited",b=l==="mentions"?"Mention History":"Citation History",C=l==="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":l==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="mentions"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":l==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="citations"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-zinc-500",children:l==="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:()=>{c(v=>v.size===m.length?new Set:new Set(m.map(k=>k.key)))},children:a.size===m.length&&m.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":g==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>x("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":g==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>x("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:b}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:m.map(({key:v,phrase:k,location:L,items:R,rawItems:I})=>{const N=a.has(v),j=R.map(T=>T.citationState),u=j.includes("cited")?"cited":j.includes("emerging")?"emerging":j.includes("lost")?"lost":j.every(T=>T==="pending")?"pending":"not-cited",E=on(R),_=R.filter(T=>T.citationState===sa.cited||T.citationState==="emerging").length,H=qn(E,l);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(v),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),d(v))},tabIndex:0,role:"button","aria-expanded":N,children:[e.jsx("td",{children:e.jsx(Is,{size:14,className:`transition-transform duration-150 text-zinc-500 ${N?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:k}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:L??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:R.map(T=>e.jsx(Ht,{provider:T.provider},T.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ln,{state:u,label:Bn(u,l)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${_} of ${R.length} engines ${C}`,children:[_,"/",R.length]})]})}),e.jsx("td",{children:e.jsx(On,{history:E})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:H}),e.jsx(_n,{items:I})]}),e.jsx("td",{})]}),N&&R.map((T,z)=>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(Ht,{provider:T.provider})}),e.jsx("td",{children:e.jsx(ln,{state:T.citationState,label:Bn(T.citationState,l)})}),e.jsx("td",{children:e.jsx(On,{history:T.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:qn(T.runHistory,l)}),e.jsx(_n,{items:[I[z]??T]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:M=>{M.stopPropagation(),i(T.id)},children:"View"})})]}),g==="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(Bc,{item:T,onViewFull:()=>i(T.id)})})]})]},T.id))]},v)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",$==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Oc(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const c=ia(a);return c.length>=4?[c]:[]}),...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 Fc(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 Bc({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}=Fc(t.answerSnippet,Tc),c=Oc(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:na(i,c)}),(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(l=>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:l},`c-${l}`)),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(l=>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:l},`co-${l}`)),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:l=>{l.stopPropagation(),s()},children:"View full answer →"})]})}function qc({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,c=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"}),c&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>{const p=i!=null&&i.toLowerCase()===l.domain.toLowerCase(),g=[a?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",p?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:g,onClick:a?()=>s(l.domain):void 0,title:a?`Filter answers to queries where ${l.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-zinc-100",children:l.domain}),e.jsx("td",{children:e.jsx(ie,{tone:aa(l.pressureLabel),children:l.pressureLabel})}),e.jsx("td",{className:"text-zinc-300 tabular-nums",children:l.totalQueries>0?`${l.citationCount} / ${l.totalQueries}`:"—"}),e.jsx("td",{className:"text-zinc-500 text-xs",children:l.citedQueries.length>0?l.citedQueries.join(", "):"Not cited"}),c&&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 ${l.domain}`,title:`Remove ${l.domain}`,onClick:x=>{x.stopPropagation(),n(l.domain)},children:"Remove"})})]},l.id)})})]})})}function Un({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:c,coverageValue:l,note:p,updatedAt:g,active:x,onClick:m}){return e.jsxs("button",{type:"button",onClick:m,className:`surface-card w-full text-left transition-colors ${x?"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(ie,{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:c})]}),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:l})]})]}),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:p}),e.jsx("span",{children:g?`Updated ${Je(g)}`:"No recent sync yet"})]})]})}function ys({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 Gc=6,Wt="__other__",Qt="_socialTotal";function _c(t,s=Gc){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const i=[...n.entries()].sort((m,d)=>d[1]!==m[1]?d[1]-m[1]:m[0].localeCompare(d[0])),a=i.slice(0,s),c=new Set(a.map(([m])=>m)),l=Math.max(0,i.length-s),p=new Map;for(const m of t){let d=p.get(m.date);d||(d={date:m.date,[Qt]:0},p.set(m.date,d));const $=c.has(m.source)?m.source:Wt;d[$]=(d[$]??0)+m.sessions,d[Qt]=(d[Qt]??0)+m.sessions}const g=[...p.values()].sort((m,d)=>String(m.date).localeCompare(String(d.date))),x=a.map(([m])=>m);return l>0&&x.push(Wt),{data:g,sources:x,otherCount:l}}function Kt(t){return t.replace(/\+/g," ")}function Ci(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Uc=["7d","30d","90d","all"],pt=Ue,dn=Qe.textDim,Ai=Qe.textFaint,ns=25,vs=50;function Ns(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function $i(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 Qc({projectName:t}){const{data:s,isLoading:n,isError:i}=mc(t);if(n)return e.jsx(W,{className:"p-5",children:e.jsx("div",{className:"text-sm text-zinc-500",children:"Loading server activity…"})});if(i)return e.jsx(W,{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(ft,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Manage sources →"})]})]})}),a.length===0?e.jsx(W,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-zinc-400",children:["No server traffic source connected yet."," ",e.jsx(ft,{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(W,{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(c=>e.jsxs("tr",{className:"border-t border-zinc-800/60",children:[e.jsx("td",{className:"px-4 py-3 text-zinc-100",children:c.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{tone:uc(c.status),children:c.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:c.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:c.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:c.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-zinc-400 text-xs",children:c.lastSyncedAt?$i(c.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(ft,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:c.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},c.id))})]})})]})}function Kc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Qc,{projectName:t}),e.jsx(Hc,{projectName:t})]})}function Hc({projectName:t}){const s=yt(),[n,i]=r.useState(null),[a,c]=r.useState(null),[l,p]=r.useState(!0),[g,x]=r.useState(!1),[m,d]=r.useState(!1),[$,b]=r.useState(null),[C,v]=r.useState(null),[k,L]=r.useState("sessions"),[R,I]=r.useState("desc"),[N,j]=r.useState("sessions"),[u,E]=r.useState("desc"),[_,H]=r.useState("sessions"),[T,z]=r.useState("desc"),[M,U]=r.useState("sessions"),[G,ne]=r.useState("desc"),[fe,xe]=r.useState(1),[pe,me]=r.useState([]),[he,je]=r.useState([]),[f,B]=r.useState([]),[te,ce]=r.useState(!1),[de,ke]=r.useState("30d");async function A(S){p(!0),b(null);try{const F=await s.fetchQuery({...ra({client:K,path:{name:t}}),staleTime:ss});if(S.current)return;if(i(F),!F.connected){c(null),me([]),je([]),B([]),p(!1);return}const Q=de==="all"?void 0:de,[Z,nt,Zt,we]=await Promise.all([s.fetchQuery({...ca({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).then(We=>We),s.fetchQuery({...la({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...oa({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...da({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[])]);if(S.current)return;c(Z),me(nt),je(Zt),B(we),p(!1)}catch(F){if(S.current)return;b(F instanceof Error?F.message:"Failed to load GA4 data"),p(!1)}}r.useEffect(()=>{const S={current:!1};return A(S),()=>{S.current=!0}},[t,de,s]);async function V(){x(!0),b(null),v(null);try{const S=await li(t);v(`Synced ${S.rowCount.toLocaleString()} page rows, ${S.aiReferralCount.toLocaleString()} AI and ${S.socialReferralCount.toLocaleString()} social referral rows (${S.days} days)`),await s.invalidateQueries({predicate:F=>{const Q=F.queryKey[0];return typeof Q?._id=="string"&&Q._id.startsWith("getApiV1ProjectsByNameGa")}}),await A({current:!1})}catch(S){b(S instanceof Error?S.message:"Sync failed")}finally{x(!1)}}async function Te(){d(!0),b(null),v(null);try{await xa(t),await s.invalidateQueries({predicate:S=>{const F=S.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),v("GA4 disconnected")}catch(S){b(S instanceof Error?S.message:"Disconnect failed")}finally{d(!1)}}function be(S){k===S?I(F=>F==="desc"?"asc":"desc"):(L(S),I("desc"))}function ye(S){N===S?E(F=>F==="desc"?"asc":"desc"):(j(S),E("desc"))}function X(S){_===S?z(F=>F==="desc"?"asc":"desc"):(H(S),z("desc"))}function O(S){xe(1),M===S?ne(F=>F==="desc"?"asc":"desc"):(U(S),ne("desc"))}const q=r.useMemo(()=>a?.topPages?[...a.topPages].sort((S,F)=>{const Q=S[k],Z=F[k];return typeof Q=="string"&&typeof Z=="string"?R==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):R==="asc"?Q-Z:Z-Q}):[],[a?.topPages,k,R]),ae=r.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((S,F)=>{const Q=S[N],Z=F[N];return typeof Q=="string"&&typeof Z=="string"?u==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):u==="asc"?Q-Z:Z-Q}):[],[a?.aiReferrals,N,u]),le=r.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((S,F)=>{const Q=S[M],Z=F[M];return typeof Q=="string"&&typeof Z=="string"?G==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):G==="asc"?Q-Z:Z-Q}):[],[a?.aiReferralLandingPages,M,G]),y=Math.max(1,Math.ceil(le.length/vs)),D=Math.min(Math.max(1,fe),y),Ce=(D-1)*vs,Oe=r.useMemo(()=>le.slice(Ce,Ce+vs),[le,Ce]),Ne=r.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((S,F)=>{const Q=S[_],Z=F[_];return typeof Q=="string"&&typeof Z=="string"?T==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):T==="asc"?Q-Z:Z-Q}):[],[a?.socialReferrals,_,T]),{socialChartData:vt,socialChartSources:dt,socialOtherCount:Ke}=r.useMemo(()=>{const S=_c(f);return{socialChartData:S.data,socialChartSources:S.sources,socialOtherCount:S.otherCount}},[f]),{chartData:Nt,chartSources:Fe,dateRange:tt}=r.useMemo(()=>{const S=[...new Set(pe.map(we=>we.source))],F=new Map;for(const we of he)F.set(we.date,{_totalSessions:we.sessions,_organicSessions:we.organicSessions});const Q=new Map;for(const we of pe){const We=`${we.date}::${we.source}`,Et=Q.get(We)??0;Q.set(We,Math.max(Et,we.sessions))}for(const[we,We]of Q){const[Et,xt]=we.split("::");let it=F.get(Et);it||(it={_totalSessions:0,_organicSessions:0},F.set(Et,it)),it[xt]=(it[xt]??0)+We}const Z=[...F.entries()].sort(([we],[We])=>we.localeCompare(We)).map(([we,We])=>({date:we,...We})),nt=Z.map(we=>we.date),Zt=nt.length>0?{start:nt[0],end:nt[nt.length-1]}:null;return{chartData:Z,chartSources:S,dateRange:Zt}},[pe,he]);if(l&&!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(Wc,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:S=>{const F=S.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),await A({current:!1})))()}});const st=a?.organicSharePctDisplay??"0%",Rt=a?.channelBreakdown?.organic.sharePctDisplay??st,wt=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,Vt=a?.aiSessionsDeduped??0,Ae=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,Yt=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",_e=a?new Set(a.aiReferrals.map(S=>S.source.toLowerCase())).size:0,Ee=ae[0]??null,zt=a?.totalDirectSessions??0,Xt=a?.directSharePctDisplay??"0%",Jt=a?.channelBreakdown?.direct.sessions??zt,xs=a?.channelBreakdown?.direct.sharePctDisplay??Xt,at=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,Ie=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",h=a?.socialSessions??0,Y=a?.socialSharePctDisplay??"0%",se=a?.channelBreakdown?.social.sessions??h,Pe=a?.channelBreakdown?.social.sharePctDisplay??Y,ve=a?new Set(a.socialReferrals.map(S=>S.source.toLowerCase())).size:0,He=Ne[0]??null;return e.jsxs(e.Fragment,{children:[$&&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:$}),C&&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:C}),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(P,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ps,{className:`w-3.5 h-3.5 mr-1.5 ${g?"animate-spin":""}`}),g?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:m,onClick:ee(Te),children:[e.jsx(wc,{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(Se,{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(S=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${de===S?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>ke(S),children:S==="all"?"All":S},S))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ws,{value:Ns(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ws,{value:Ns(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${st} of total`,tone:"positive"}),e.jsx(Ws,{value:Ns(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(P,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ps,{className:`w-3.5 h-3.5 mr-1.5 ${g?"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(Se,{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."})]})]}),tt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(tt.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(tt.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Nt.length>0&&e.jsxs(W,{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:Fe.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Fe.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Fe.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(Pt,{width:"100%",height:"100%",children:e.jsxs(Lt,{data:Nt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:Ge,tickLine:!1,axisLine:{stroke:et},tickFormatter:$t}),e.jsx(Tt,{tick:Ge,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ot,labelFormatter:jt,formatter:(S,F)=>{const Q=typeof S=="number"?S.toLocaleString():String(S??0),Z=String(F??"");return Z==="_totalSessions"?[Q,"Total Sessions"]:Z==="_organicSessions"?[Q,"Organic Sessions"]:[Q,Z]}}),e.jsx(ji,{wrapperStyle:{fontSize:11,color:Qe.text},formatter:S=>S==="_totalSessions"?"Total Sessions":S==="_organicSessions"?"Organic Sessions":S}),e.jsx(qt,{type:"monotone",dataKey:"_totalSessions",stroke:Qe.textFaint,fill:Qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Fe.map((S,F)=>e.jsx(qt,{type:"monotone",dataKey:S,stackId:"ai",stroke:pt[F%pt.length],fill:pt[F%pt.length],fillOpacity:.4,strokeWidth:1.5},S))]})})})]}),e.jsxs(W,{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(Ze,{label:"Organic",value:Rt,hint:`${wt.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(Ze,{label:"Social",value:Pe,hint:`${se.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(Ze,{label:"Direct",value:xs,hint:`${Jt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(Ze,{label:"Known AI referrers (lower bound)",value:Yt,hint:`${Ae.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(Ze,{label:"Other channels",value:Ie,hint:`${at.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."})]}),Ee&&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:Ee.source})," via ",Ee.medium,", accounting for ",Ee.sessions.toLocaleString()," sessions."]})]}),e.jsxs(W,{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?`${_e} 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(Me,{label:"Source",sortKey:"source",current:N,dir:u,onSort:ye,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:N,dir:u,onSort:ye,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:N,dir:u,onSort:ye,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:N,dir:u,onSort:ye,align:"right"})]})}),e.jsx("tbody",{children:ae.map(S=>e.jsx(Yc,{referral:S,totalSessions:Vt},`${S.source}:${S.medium}:${S.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(W,{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:le.length>vs?`${Ce+1}–${Ce+Oe.length} of ${le.length} rows`:le.length>0?`${le.length} rows`:"No landing-page rows"})]}),le.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(Me,{label:"Landing Page",sortKey:"landingPage",current:M,dir:G,onSort:O,align:"left"}),e.jsx(Me,{label:"Source",sortKey:"source",current:M,dir:G,onSort:O,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:M,dir:G,onSort:O,align:"right"}),e.jsx(Me,{label:"Users",sortKey:"users",current:M,dir:G,onSort:O,align:"right"})]})}),e.jsx("tbody",{children:Oe.map(S=>e.jsx(Xc,{row:S},`${S.landingPage}:${S.source}:${S.medium}:${S.sourceDimension}`))})]})}),y>1&&e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>xe(D-1),disabled:D<=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 ",D," of ",y]}),e.jsx("button",{type:"button",onClick:()=>xe(D+1),disabled:D>=y,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(Se,{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."})]})]}),vt.length>0&&e.jsxs(W,{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"})]}),Ke>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",dt.length-1," sources · ",Ke," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Lt,{data:vt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:Ge,tickLine:!1,axisLine:{stroke:et},tickFormatter:$t}),e.jsx(Tt,{tick:Ge,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ot,labelFormatter:jt,formatter:(S,F)=>{const Q=typeof S=="number"?S.toLocaleString():String(S??0),Z=String(F??"");if(Z===Qt)return[Q,"Total Social"];if(Z===Wt){const nt=`Other (${Ke} source${Ke===1?"":"s"})`;return[Q,nt]}return[Q,Kt(Z)]}}),e.jsx(qt,{type:"monotone",dataKey:Qt,stroke:Ai,fill:Qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),dt.map((S,F)=>{const Z=S===Wt?dn:pt[F%pt.length];return e.jsx(qt,{type:"monotone",dataKey:S,stackId:"social",stroke:Z,fill:Z,fillOpacity:.4,strokeWidth:1.5},S)})]})})}),e.jsx(Zc,{sources:dt,otherCount:Ke})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(W,{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(Ze,{label:"Social Sessions",value:Ns(h),hint:`${h.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Ze,{label:"Share of Traffic",value:Y,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Ze,{label:"Platforms",value:String(ve),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."})]}),He&&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:`${He.source} via ${He.medium}`,children:Ci(Kt(He.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:He.medium,children:["via ",Kt(He.medium)," · ",He.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(Ze,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Ze,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Ze,{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(W,{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?Ne.length>ns&&!te?`Top ${ns} of ${Ne.length}`:`${Ne.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(Me,{label:"Source",sortKey:"source",current:_,dir:T,onSort:X,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:_,dir:T,onSort:X,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:_,dir:T,onSort:X,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:_,dir:T,onSort:X,align:"right"})]})}),e.jsx("tbody",{children:(te?Ne:Ne.slice(0,ns)).map(S=>e.jsx(Jc,{referral:S,totalSessions:h},`${S.source}:${S.medium}:${S.channelGroup}`))})]})}),Ne.length>ns&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ce(S=>!S),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:te?`Show top ${ns}`:`Show all ${Ne.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(Se,{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(Me,{label:"Landing Page",sortKey:"landingPage",current:k,dir:R,onSort:be,align:"left"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:k,dir:R,onSort:be,align:"right"}),e.jsx(Me,{label:"Organic",sortKey:"organicSessions",current:k,dir:R,onSort:be,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Me,{label:"Users",sortKey:"users",current:k,dir:R,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:q.map(S=>e.jsx(Vc,{page:S},S.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 ${$i(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function Wc({projectName:t,onConnected:s}){const[n,i]=r.useState(""),[a,c]=r.useState(null),[l,p]=r.useState(null),[g,x]=r.useState(!1),[m,d]=r.useState(null),$=r.useRef(null),b=r.useCallback(v=>{const k=v.target.files?.[0];if(!k)return;d(null),c(k.name);const L=new FileReader;L.onload=()=>{const R=L.result;try{const I=JSON.parse(R);if(!I.client_email||!I.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)."),p(null);return}p(R)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),p(null)}},L.onerror=()=>{d("Failed to read file."),p(null)},L.readAsText(k)},[]);async function C(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!l){d("Please upload a service account key file.");return}x(!0);try{await ma(t,{propertyId:n.trim(),keyJson:l});try{await li(t)}catch{}s()}catch(v){d(v instanceof Error?v.message:"Failed to connect GA4")}finally{x(!1)}}return e.jsxs(W,{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."}),m&&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:m}),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:v=>i(v.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:$,type:"file",accept:".json,application/json",onChange:b,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>$.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(Sc,{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(P,{variant:"default",size:"sm",disabled:g||!n.trim()||!l,onClick:ee(C),children:g?"Connecting & syncing…":"Connect GA4"})]})}function Me({label:t,sortKey:s,current:n,dir:i,onSort:a,align:c}){const l=n===s;return e.jsx("th",{className:`py-1 ${c==="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}${l?` (currently ${i==="asc"?"ascending":"descending"})`:""}`,children:[t,l&&e.jsx("span",{className:"ml-0.5",children:i==="asc"?"↑":"↓"})]})})}const Pi={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function Ws({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 ${Pi[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Ze({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(Se,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Pi[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Vc({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 Li={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Di={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 Yc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=Li[t.sourceDimension]??t.sourceDimension,a=Di[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 Xc({row:t}){const s=Li[t.sourceDimension]??t.sourceDimension,n=Di[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 Jc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Kt(t.source),c=Kt(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:c}),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 Zc({sources:t,otherCount:s}){const n=[{key:Qt,color:Ai,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===Wt)n.push({key:Wt,color:dn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const c=Kt(a);n.push({key:a,color:pt[i%pt.length]??dn,label:Ci(c,32),tooltip:c})}}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 el(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 tl=["7d","30d","90d","all"],ws=500,ut=25;function sl({projectName:t,refreshNonce:s}){const n=yt(),[i,a]=r.useState(!1),[c,l]=r.useState([]),[p,g]=r.useState([]),[x,m]=r.useState([]),[d,$]=r.useState(null),[b,C]=r.useState([]),[v,k]=r.useState([]),[L,R]=r.useState(null),[I,N]=r.useState(""),[j,u]=r.useState(""),[E,_]=r.useState("30"),[H,T]=r.useState(!1),[z,M]=r.useState("30d"),[U,G]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[ne,fe]=r.useState(0),[xe,pe]=r.useState(!1),[me,he]=r.useState(0),[je,f]=r.useState(!1),[B,te]=r.useState(""),[ce,de]=r.useState(!0),[ke,A]=r.useState(!1),[V,Te]=r.useState(!1),[be,ye]=r.useState(!1),[X,O]=r.useState(!1),[q,ae]=r.useState(!1),[le,y]=r.useState(!1),[D,Ce]=r.useState(null),[Oe,Ne]=r.useState(!1),[vt,dt]=r.useState(!1),[Ke,Nt]=r.useState(null),[Fe,tt]=r.useState(""),[st,Rt]=r.useState(!1),[wt,Vt]=r.useState(!1),[Ae,Yt]=r.useState("indexed"),[_e,Ee]=r.useState(null),zt=!!(U.query.trim()||U.page.trim()||_e),Xt=_e!==null,Jt=r.useMemo(()=>{if(!_e)return x;const{key:o,dir:w}=_e;return[...x].sort((J,oe)=>{const Le=o===At.CTR?Number.isFinite(J.ctr)?J.ctr:0:J[o],qe=o===At.CTR?Number.isFinite(oe.ctr)?oe.ctr:0:oe[o];return w==="asc"?Le-qe:qe-Le})},[x,_e]),[xs,at]=r.useState([]),[Ie,h]=r.useState(null),[Y,se]=r.useState(1);r.useEffect(()=>{se(1)},[D,Ae,Ie]);const Pe=r.useMemo(()=>Ie?(D?.reasonGroups??[]).find(o=>o.reason===Ie):void 0,[D,Ie]),ve=r.useMemo(()=>D?Ae==="indexed"?D.indexed:Ae==="deindexed"?D.deindexed:Ae==="notIndexed"?Ie?Pe?.urls??[]:(D.reasonGroups??[]).length===0?D.notIndexed:[]:[]:[],[D,Ae,Ie,Pe]),He=Math.max(1,Math.ceil(ve.length/ut)),S=Math.min(Math.max(1,Y),He),F=(S-1)*ut,Q=ve.length>ut,Z=ve.length===0?0:F+1,nt=Math.min(F+ut,ve.length),Zt=r.useMemo(()=>D?.indexed.slice(F,F+ut)??[],[D,F]),we=r.useMemo(()=>D?.notIndexed.slice(F,F+ut)??[],[D,F]),We=r.useMemo(()=>D?.deindexed.slice(F,F+ut)??[],[D,F]),Et=r.useMemo(()=>(Pe?.urls??[]).slice(F,F+ut),[Pe,F]),[xt,it]=r.useState(!1),[jn,ue]=r.useState(null),[rt,ms]=r.useState(null),[yn,ct]=r.useState(null);function Fi(o,w){const J=hc(o),oe=el(J);oe?(ms(oe),ue(null)):(ms(null),ue(J.message||w))}const ze=c.find(o=>o.connectionType==="gsc"),Bi=x.length>0||b.length>0||v.length>0,qs=ua(),es=ha(),Gs=pa();async function vn(o){if(!o){g([]),N("");return}Te(!0);try{const{sites:w}=await n.fetchQuery({...Ca({client:K,path:{name:t}}),staleTime:Re});g(w),N(o.propertyId??w[0]?.siteUrl??""),ms(null)}catch(w){g([]),Fi(w,"Failed to load Search Console properties")}finally{Te(!1)}}async function Mt(o){O(!0);const w=o??ne;try{const J=parseInt(U.limit,10)||20,oe=zt?ws:J+1,Le=zt?0:w,qe={limit:String(oe)};U.startDate&&(qe.startDate=U.startDate),U.endDate&&(qe.endDate=U.endDate),U.query&&(qe.query=U.query),U.page&&(qe.page=U.page),Le>0&&(qe.offset=String(Le)),z&&z!=="all"&&!U.startDate&&(qe.window=z);const Ve=await n.fetchQuery({...ba({client:K,path:{name:t},query:qe}),staleTime:Re});zt?(pe(!1),m(Ve),he(Ve.length),f(!0)):(pe(Ve.length>J),m(Ve.slice(0,J)),he(0),f(!1))}catch(J){m([]),pe(!1),he(0),ue(J instanceof Error?J.message:"Failed to load GSC performance data")}finally{O(!1)}}async function _s(){try{const o={};U.startDate&&(o.startDate=U.startDate),U.endDate&&(o.endDate=U.endDate),z&&z!=="all"&&!U.startDate&&(o.window=z);const w=await n.fetchQuery({...ja({client:K,path:{name:t},query:o}),staleTime:Re});$(w)}catch{$(null)}}async function us(){ae(!0);try{const o=B.trim()||void 0,w={limit:"20"};o&&(w.url=o);const[J,oe]=await Promise.all([n.fetchQuery({...Sa({client:K,path:{name:t},query:w}),staleTime:Re}),n.fetchQuery({...ka({client:K,path:{name:t}}),staleTime:Re})]);C(J),k(oe)}catch(o){C([]),k([]),ue(o instanceof Error?o.message:"Failed to load GSC inspection history")}finally{ae(!1)}}async function Nn(){Ne(!0);try{const[o,w]=await Promise.all([n.fetchQuery({...oi({client:K,path:{name:t}}),staleTime:Re}),n.fetchQuery({...wa({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);Ce(o),at(w)}catch(o){Ce(null),at([]),ue(o instanceof Error?o.message:"Failed to load coverage data")}finally{Ne(!1)}}async function wn(o){it(!0),ue(null);try{const w=await Pn(t,{urls:o}),{succeeded:J,failed:oe,total:Le}=w.summary;re({title:"Indexing requested",detail:oe===0?`${J} URL${J!==1?"s":""} submitted for indexing.`:`${J}/${Le} submitted successfully, ${oe} failed.`,tone:oe===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(w){ue(w instanceof Error?w.message:"Failed to request indexing")}finally{it(!1)}}async function qi(){it(!0),ue(null);try{const o=await Pn(t,{urls:[],allUnindexed:!0}),{succeeded:w,failed:J,total:oe}=o.summary;re({title:"Indexing requested",detail:J===0?`${w} unindexed URL${w!==1?"s":""} submitted for indexing.`:`${w}/${oe} submitted successfully, ${J} failed.`,tone:J===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(o){ue(o instanceof Error?o.message:"Failed to request indexing")}finally{it(!1)}}async function hs(){if(Fe.trim()){Rt(!0),ue(null);try{await Na(t,"gsc",Fe.trim()),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(o=>o.map(w=>w.connectionType==="gsc"?{...w,sitemapUrl:Fe.trim()}:w)),re({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),tt("")}catch(o){ue(o instanceof Error?o.message:"Failed to save sitemap URL")}finally{Rt(!1)}}}async function zn(){ue(null);try{const o=await es.mutateAsync({projectName:t,projectLabel:t});Nt(o.sitemaps),l(w=>w.map(J=>J.connectionType==="gsc"?{...J,sitemapUrl:o.primarySitemapUrl}:J))}catch{}}async function Gi(){dt(!0),ue(null);try{const o=await $a(t);n.setQueryData(Pa({client:K,path:{name:t}}),o),Nt(o.sitemaps),o.sitemaps.length===0&&ct("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(o){ue(o instanceof Error?o.message:"Failed to list sitemaps")}finally{dt(!1)}}async function Sn(){de(!0),ue(null);try{const[o,w]=await Promise.all([fa().catch(()=>null),n.fetchQuery({...un({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);a(!!o?.google?.configured),l(w);const J=w.find(oe=>oe.connectionType==="gsc");await Promise.all([vn(J),Mt(),_s(),us(),Nn()])}finally{de(!1)}}r.useEffect(()=>{Sn()},[t,s]),r.useEffect(()=>{fe(0),Mt(0),_s()},[z]);const kn=r.useRef(!1);r.useEffect(()=>{if(!kn.current){kn.current=!0;return}fe(0),Mt(0)},[Xt]);async function _i(){if(!i){ue("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}A(!0),ue(null),ct(null);try{const{authUrl:o}=await va(t,"gsc");if(!o.startsWith("https://accounts.google.com/")){ue("Unexpected OAuth redirect URL. Please try again.");return}const w=window.open(o,"_blank","width=600,height=700");if(!w){window.location.assign(o);return}ct("Finish the Google consent flow in the popup, then close it to refresh this project.");const J=window.setInterval(()=>{w.closed&&(window.clearInterval(J),ct(null),n.invalidateQueries({predicate:oe=>{const Le=oe.queryKey[0];return typeof Le?._id=="string"&&Le._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),Sn())},1e3)}catch(o){ue(o instanceof Error?o.message:"Failed to start OAuth flow")}finally{A(!1)}}async function Ui(){ue(null),ct(null);try{await ya(t,"gsc"),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(o=>o.filter(w=>w.connectionType!=="gsc")),g([]),N("")}catch(o){ue(o instanceof Error?o.message:"Failed to disconnect")}}async function Qi(){if(I){ye(!0),ue(null);try{await Aa(t,"gsc",I),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(o=>o.map(w=>w.connectionType==="gsc"?{...w,propertyId:I}:w)),re({title:"GSC property updated",detail:`${t} is now linked to ${I}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(o){ue(o instanceof Error?o.message:"Failed to save GSC property")}finally{ye(!1)}}}async function Ki(){ue(null),ct(null);try{await qs.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(E,10)||void 0,full:H||void 0}}),await n.invalidateQueries({predicate:o=>{const w=o.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function Cn(){if(j.trim()){y(!0),ue(null),ct(null);try{const o=await za(t,j.trim());await n.invalidateQueries({predicate:w=>{const J=w.queryKey[0];return typeof J?._id=="string"&&J._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),R(o),u(""),await us()}catch(o){ue(o instanceof Error?o.message:"Failed to inspect URL")}finally{y(!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"})]})}),rt&&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:rt.title}),e.jsx("p",{className:"mt-0.5 text-amber-200/90",children:rt.message}),(Bt(rt.enableUrl)||Bt(rt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Bt(rt.enableUrl)&&e.jsx("a",{href:Bt(rt.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 ↗"}),Bt(rt.indexingApiUrl)&&e.jsx("a",{href:Bt(rt.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:()=>ms(null),children:"×"})]})}),jn&&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:[jn,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>ue(null),children:"×"})]}),yn&&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:[yn,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>ct(null),children:"×"})]}),ce?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[ze?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:ze.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Je(ze.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:ee(Ui),children:"Disconnect"})]}):e.jsxs(W,{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(ie,{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(P,{type:"button",variant:"outline",size:"sm",disabled:ke,onClick:ee(_i),children:ke?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ft,{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."})]})]})]}),ze&&!ze.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(P,{type:"button",size:"sm",disabled:es.isPending||!ze.propertyId,onClick:ee(zn),children:es.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:Fe,onChange:o=>tt(o.target.value),onKeyDown:o=>o.key==="Enter"&&void hs()}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:st||!Fe.trim(),onClick:ee(hs),children:st?"Saving…":"Save sitemap URL"})]})]})]})]})}),(ze||Bi)&&e.jsxs(e.Fragment,{children:[e.jsxs(W,{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:[D&&D.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{qi()},children:xt?"Requesting…":`Request indexing (${D.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Oe,onClick:()=>{Nn()},children:Oe?"Loading…":"Refresh coverage"})]})]}),D&&D.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const o=D.summary.indexed+D.summary.notIndexed,w=o>0?D.summary.indexed/o:0,J=o>0?D.summary.notIndexed/o:0,oe=54,Le=2*Math.PI*oe,qe=Le*(1-w),Ve=Le*J,Ot=Le*w;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:oe,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:oe,fill:"none",stroke:bt.positiveDeep,strokeWidth:"14",strokeDasharray:Le,strokeDashoffset:qe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),D.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:oe,fill:"none",stroke:Qe.textFaint,strokeWidth:"14",strokeDasharray:`${Ve} ${Le-Ve}`,strokeDashoffset:-Ot,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:[(w*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:D.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:D.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:["Not indexed",(D.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-zinc-600",children:["· ",(D.reasonGroups??[]).length," ",(D.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),D.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:D.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(o=>{const w=o==="indexed"?D.indexed.length:o==="notIndexed"?D.notIndexed.length:D.deindexed.length,J=o==="indexed"?"Indexed":o==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${Ae===o?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{Yt(o),h(null)},children:[J," (",w,")"]},o)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ae==="indexed"&&D.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:Zt.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-400",children:o.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:o.crawlTime?o.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:o.isMobileFriendly===!0?"Yes":o.isMobileFriendly===!1?"No":"—"})]},o.id))})]}),Ae==="notIndexed"&&!Ie&&(D.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:(D.reasonGroups??[]).map(o=>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:()=>h(o.reason),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),h(o.reason))},tabIndex:0,role:"button","aria-label":`View ${o.reason} pages`,children:[e.jsx("td",{className:"text-zinc-200",children:o.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:o.count})]},o.reason))})]}),Ae==="notIndexed"&&!Ie&&(D.reasonGroups??[]).length===0&&D.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:we.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-400",children:o.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:o.coverageState??"Unknown"})]},o.id))})]}),Ae==="notIndexed"&&Ie&&(()=>{const o=(D.reasonGroups??[]).find(w=>w.reason===Ie);return o?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:()=>h(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:o.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[o.count," affected page",o.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:xt,onClick:()=>{wn(o.urls.map(w=>w.url))},children:xt?"Requesting…":`Request indexing (${o.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:Et.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:w.url}),e.jsx("td",{className:"text-zinc-400",children:w.crawlTime?w.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:()=>{wn([w.url])},title:"Request indexing",children:"Index"})})]},w.id))})]})]}):null})(),Ae==="deindexed"&&D.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:We.map((o,w)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-400",children:o.previousState}),e.jsx("td",{className:"text-zinc-400",children:o.currentState}),e.jsx("td",{className:"text-zinc-400",children:o.transitionDate.split("T")[0]})]},`${o.url}-${w}`))})]}),(Ae==="indexed"&&D.indexed.length===0||Ae==="notIndexed"&&!Ie&&D.notIndexed.length===0||Ae==="deindexed"&&D.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:Z.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-zinc-300",children:nt.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-zinc-300",children:ve.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>se(o=>Math.max(1,o-1)),disabled:S<=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(dc,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-zinc-200",children:S})," of"," ",e.jsx("span",{className:"text-zinc-200",children:He})]}),e.jsxs("button",{type:"button",onClick:()=>se(o=>Math.min(He,o+1)),disabled:S>=He,"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(Is,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:Oe?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(W,{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:tl.map(o=>e.jsx("button",{type:"button",role:"tab","aria-selected":z===o,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${z===o?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>M(o),children:o==="all"?"All":o},o))}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:X,onClick:()=>{fe(0),Mt(0),_s()},children:X?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const o=d.daily,w=Math.max(...o.map(ge=>ge.impressions),1),{clicks:J,impressions:oe,ctr:Le}=d.totals,qe=(Le*100).toFixed(1),Ve=700,Ot=220,Ye={top:12,bottom:36,left:48,right:12},Hi=Ve-Ye.left-Ye.right,Ft=Ot-Ye.top-Ye.bottom,ts=Hi/o.length,ps=Math.max(Math.min(ts*.35,24),4),An=Math.max(ps*.15,1),Wi=ge=>{if(ge<=0)return 1;const lt=Math.pow(10,Math.floor(Math.log10(ge))),Xe=ge/lt,mt=Xe<=1.5?1.5:Xe<=3?3:Xe<=5?5:10;return Math.ceil(mt*lt)},gs=4,fs=Math.ceil(Wi(w)/gs)*gs,Vi=Array.from({length:gs+1},(ge,lt)=>fs/gs*lt),Yi=ge=>ge>=1e3?`${(ge/1e3).toFixed(ge>=1e4?0:1)}k`:String(ge);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:J.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:oe.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[qe,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ve} / ${Ot}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ve} ${Ot}`,className:"h-full w-full",children:[Vi.map((ge,lt)=>{const Xe=Ye.top+Ft-ge/fs*Ft;return e.jsxs("g",{children:[e.jsx("line",{x1:Ye.left,y1:Xe,x2:Ve-Ye.right,y2:Xe,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:Ye.left-6,y:Xe+3.5,textAnchor:"end",fill:Qe.text,fontSize:"10",fontFamily:"inherit",children:Yi(ge)})]},`t-${lt}`)}),o.map((ge,lt)=>{const Xe=Ye.left+ts*lt+ts/2,mt=ge.impressions/fs*Ft,bs=ge.clicks/fs*Ft;return e.jsxs("g",{children:[e.jsx("title",{children:`${ge.date}
2
2
  Clicks: ${ge.clicks}
3
3
  Impressions: ${ge.impressions}
4
4
  CTR: ${(ge.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Xe-ps-An/2,y:Ye.top+Ft-mt,width:ps,height:Math.max(mt,1),rx:2,fill:Ue[1],opacity:.85}),e.jsx("rect",{x:Xe+An/2,y:Ye.top+Ft-bs,width:ps,height:Math.max(bs,1),rx:2,fill:bt.positiveDeep,opacity:.85})]},ge.date)}),(()=>{const ge=Math.min(o.length,7);return Array.from({length:ge},(lt,Xe)=>{const mt=o.length===1?0:Math.round(Xe/(ge-1)*(o.length-1)),bs=Ye.left+ts*mt+ts/2;return e.jsx("text",{x:bs,y:Ot-8,textAnchor:"middle",fill:Qe.textDim,fontSize:"10",fontFamily:"inherit",children:o[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:U.startDate,onChange:o=>G(w=>({...w,startDate:o.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:U.endDate,onChange:o=>G(w=>({...w,endDate:o.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:U.query,onChange:o=>G(w=>({...w,query:o.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:U.page,onChange:o=>G(w=>({...w,page:o.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:U.limit,onChange:o=>G(w=>({...w,limit:o.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 ",ws.toLocaleString()," matching rows load so sorting covers the full set."]}),x.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(At).map(o=>e.jsx("th",{className:"text-right","aria-sort":_e?.key===o?_e.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:()=>Ee(w=>w?.key===o?w.dir==="desc"?{key:o,dir:"asc"}:null:{key:o,dir:"desc"}),children:[ga[o],_e?.key===o?_e.dir==="desc"?" ↓":" ↑":""]})},o))]})}),e.jsx("tbody",{children:Jt.map((o,w)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-400",children:o.date}),e.jsx("td",{className:"max-w-xs truncate text-zinc-200",children:o.query}),e.jsx("td",{className:"max-w-xs truncate text-zinc-400",children:o.page}),e.jsx("td",{className:"text-right tabular-nums text-zinc-300",children:o.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:o.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-400",children:[(Number.isFinite(o.ctr)?o.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:o.position.toFixed(1)})]},`${o.date}:${o.query}:${o.page}:${w}`))})]})}),je?e.jsx("div",{className:"mt-3 text-xs text-zinc-500",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",me.toLocaleString()," matching row",me===1?"":"s",me>=ws?` (capped at ${ws.toLocaleString()} — narrow the filter to see more)`:""]})}):(ne>0||xe)&&(()=>{const o=parseInt(U.limit,10)||20,w=ne+1,J=ne+x.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 ",w.toLocaleString()," – ",J.toLocaleString(),xe?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:X||ne===0,onClick:()=>{const oe=Math.max(0,ne-o);fe(oe),Mt(oe)},children:"Previous"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:X||!xe,onClick:()=>{const oe=ne+o;fe(oe),Mt(oe)},children:"Next"})]})]})})()]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No performance rows match the current filters yet."})]}),e.jsxs(W,{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:j,onChange:o=>u(o.target.value),onKeyDown:o=>o.key==="Enter"&&void Cn()}),e.jsx(P,{type:"button",size:"sm",disabled:le||!ze?.propertyId||!j.trim(),onClick:ee(Cn),children:le?"Inspecting…":"Inspect URL"})]}),L&&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:L.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:L.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:$n(L.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:Je(L.crawlTime)})]})]})]}),e.jsxs(W,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:q,onClick:()=>{us()},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:B,onChange:o=>te(o.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:q,onClick:()=>{us()},children:"Apply filter"})]}),b.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"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:b.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-300",children:o.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:o.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:o.coverageState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:$n(o.isMobileFriendly??null)}),e.jsx("td",{className:"text-zinc-400",children:Je(o.inspectedAt)})]},o.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No inspection history yet."})]}),e.jsxs(W,{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"})]})}),v.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:v.map(o=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:o.url}),e.jsx("td",{className:"text-zinc-400",children:o.previousState??"Unknown"}),e.jsx("td",{className:"text-zinc-300",children:o.currentState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:Je(o.transitionDate)})]},`${o.url}:${o.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No deindexed transitions recorded."})]})]}),ze&&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(o=>!o),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 ${wt?"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"})]})}),wt&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(W,{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:I,disabled:V||p.length===0,onChange:o=>N(o.target.value),children:p.length===0?e.jsx("option",{value:"",children:V?"Loading properties…":"No properties available"}):p.map(o=>e.jsxs("option",{value:o.siteUrl,children:[o.siteUrl," · ",o.permissionLevel]},o.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:V,onClick:()=>{vn(ze)},children:V?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!I||be,onClick:ee(Qi),children:be?"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(W,{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:E,onChange:o=>_(o.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:H,onChange:o=>T(o.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:qs.isPending||!ze.propertyId,onClick:ee(Ki),children:qs.isPending?"Queueing…":"Queue sync"}),!ze.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property before queueing a sync."})]})]})]}),e.jsxs(W,{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:[ze.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:ze.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:vt||!ze.propertyId,onClick:()=>{Gi()},children:vt?"Loading…":"Browse sitemaps from GSC"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:es.isPending||!ze.propertyId,onClick:ee(zn),children:es.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."}),Ke&&Ke.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 (",Ke.length,")"]}),Ke.map(o=>{const w=o.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:o.path}),o.lastSubmitted&&e.jsxs("p",{className:"text-zinc-500",children:["Submitted: ",o.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[w&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-zinc-300",children:[w.indexed," / ",w.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:()=>tt(o.path),children:"Use"})]})]},o.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:ze.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:Fe,onChange:o=>tt(o.target.value),onKeyDown:o=>o.key==="Enter"&&Fe.trim()&&void hs()}),e.jsx(P,{type:"button",size:"sm",disabled:st||!Fe.trim(),onClick:ee(hs),children:st?"Saving…":ze.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(P,{type:"button",size:"sm",variant:"outline",disabled:Gs.isPending||!ze.propertyId,onClick:ee(async()=>{const w=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||ze.sitemapUrl||void 0;ue(null),ct(null);try{await Gs.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:w}})}catch{}}),children:Gs.isPending?"Queueing…":"Inspect sitemap"})]}),!ze.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}const nl=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function il({projectName:t,projectId:s}){const n=yt(),[i,a]=r.useState(null),[c,l]=r.useState(null),[p,g]=r.useState(!1),x=$e(un({client:K,path:{name:t}})),m=x.data?.find(A=>A.connectionType==="gbp"),d=!!m,$=i?{locationName:i}:void 0,b=$e({...La({client:K,path:{name:t}}),enabled:d}),C=$e({...Da({client:K,path:{name:t},query:$}),enabled:d}),v=$e({...Ta({client:K,path:{name:t},query:$}),enabled:d}),k=$e({...Ia({client:K,path:{name:t},query:$}),enabled:d}),L=$e({...Ra({client:K,path:{name:t},query:$}),enabled:d}),R=$e({...Ea({client:K,path:{name:t},query:$}),enabled:d}),I=$e({queryKey:["gbp-section-insights",t],queryFn:()=>Ma(t),enabled:d});function N(){n.invalidateQueries({predicate:A=>{const V=A.queryKey[0];return typeof V?._id=="string"&&V._id.startsWith("getApiV1ProjectsByNameGbp")}})}const j=ls({...Fa(),onSuccess:A=>{Oa({id:A.runId,projectId:s,kind:os["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),re({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),u=r.useSyncExternalStore(Ba,Ln,Ln),E=Object.values(u.runs).some(A=>A.kind===os["gbp-sync"]&&A.projectId===s),_=j.isPending||E,H=ls({...qa(),onSuccess:()=>N()});if(r.useEffect(()=>{if(!i||!b.data)return;const A=b.data.locations.filter(V=>V.selected);(A.length<=1||!A.some(V=>V.locationName===i))&&a(null)},[i,b.data]),r.useEffect(()=>{if(!c||!b.data)return;(i?[i]:b.data.locations.filter(V=>V.selected).map(V=>V.locationName)).includes(c)||l(null)},[c,b.data,i]),x.isLoading)return null;if(!m){const A=[{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(W,{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:A.map((V,Te)=>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:Te+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:V.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:V.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-zinc-500",children:V.note})]})]},V.title))})]})})}const T=C.data,z=b.data?.locations??[],M=z.filter(A=>A.selected),U=v.data?.keywords??[],G=k.data?.lodging??[],ne=L.data?.placeActions??[],fe=R.data?.places??[],xe=z.length>0?z[0].accountName:m.domain,pe=i?z.find(A=>A.locationName===i)?.displayName??null:null,me=i?z.filter(A=>A.locationName===i):M,he=new Set(me.map(A=>A.locationName)),je=G.filter(A=>he.has(A.locationName)),f=ne.filter(A=>he.has(A.locationName)),B=fe.filter(A=>he.has(A.locationName)),te=new Set(M.map(A=>A.locationName)),ce=i?U:U.filter(A=>te.has(A.locationName)),de=!i&&M.length>1,ke=(I.data??[]).filter(A=>!A.dismissed&&nl.has(A.type)&&(!pe||A.query===pe||A.query===i||A.title.startsWith(pe)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(W,{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(Se,{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(ie,{tone:"positive",children:"Connected"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:_,onClick:()=>j.mutate({client:K,path:{name:t},body:{}}),children:_?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-zinc-500",children:[xe?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-zinc-400",children:xe})," · "]}):null,b.data?`${b.data.totalSelected} of ${b.data.totalDiscovered} locations tracked`:"Loading locations…"]}),M.length>1&&e.jsxs("div",{className:"mb-5 flex flex-wrap gap-1.5",role:"tablist","aria-label":"Location",children:[e.jsx(Qn,{label:"All locations",active:i===null,onClick:()=>a(null)}),M.map(A=>e.jsx(Qn,{label:A.displayName,active:i===A.locationName,onClick:()=>a(A.locationName)},A.id))]}),M.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:[ke.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ke.map(A=>e.jsx("div",{className:["insight-card",fl(A.severity),"rounded-r-lg border border-zinc-800/60 bg-zinc-900/30 p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-zinc-200",children:[A.title,A.recommendation?.reason&&e.jsx(Se,{text:A.recommendation.reason})]})},A.id))]}),T&&e.jsx(vl,{performance:T.performance,freshness:T.freshness,timeseries:T.timeseries}),T?.profileCompleteness&&e.jsx(al,{summary:T.profileCompleteness}),me.length>0&&e.jsx(rl,{locations:me,lodging:je,places:B,placeActions:f,expandedLocation:c,onToggleExpanded:A=>{l(V=>V===A?null:A)}}),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"}),v.data&&v.data.total>0&&e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[v.data.thresholdedPct,"% privacy-thresholded"]})]}),ce.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"}),de&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:ce.slice(0,25).map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-300",children:A.keyword}),de&&e.jsx("td",{className:"text-zinc-500",children:z.find(V=>V.locationName===A.locationName)?.displayName??A.locationName}),e.jsx("td",{className:"text-right font-mono text-zinc-200",children:A.valueCount!==null?A.valueCount.toLocaleString():e.jsxs("span",{className:"text-zinc-500",title:"Privacy floor — Google withheld the exact count",children:["<",A.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-zinc-600",children:[A.periodStart,"–",A.periodEnd]})]},`${A.locationName}:${A.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:()=>g(A=>!A),"aria-expanded":p,children:[e.jsx("span",{"aria-hidden":"true",children:p?"▾":"▸"})," Manage locations (",z.length,")"]}),p&&e.jsx("div",{className:"mt-3",children:z.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:z.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-200",children:A.displayName}),e.jsx("td",{className:"text-zinc-500",children:A.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ie,{tone:A.selected?"positive":"neutral",children:A.selected?"Tracked":"Not tracked"})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:H.isPending,onClick:()=>H.mutate({client:K,path:{name:t,locationName:A.locationName},body:{selected:!A.selected}}),children:A.selected?"Untrack":"Track"})})]},A.id))})]})})]})]})})}function Qn({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 al({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:is(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:is(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:is(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:is(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:is(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-zinc-800/60 py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Se,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(i=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-zinc-500",children:i.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${gl(i.tone)}`,children:i.value}),i.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-zinc-600",children:i.detail})]},i.label))})]})}function rl({locations:t,lodging:s,places:n,placeActions:i,expandedLocation:a,onToggleExpanded:c}){const l=new Map(s.map(x=>[x.locationName,x])),p=new Map(n.map(x=>[x.locationName,x])),g=new Map;for(const x of i){const m=g.get(x.locationName)??[];m.push(x),g.set(x.locationName,m)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Se,{text:"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(x=>{const m=l.get(x.locationName)??null,d=p.get(x.locationName)??null,$=g.get(x.locationName)??[],b=a===x.locationName;return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-zinc-200",children:x.displayName}),e.jsx("p",{className:"mt-1 text-xs text-zinc-600",children:x.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ie,{tone:x.selected?"positive":"neutral",children:x.selected?"Tracked":"Not tracked"}),x.openStatus&&x.openStatus!=="OPEN"&&e.jsx(ie,{tone:x.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ti(x.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(ll,{location:x})}),e.jsx("td",{children:e.jsx(ol,{lodging:m})}),e.jsx("td",{children:e.jsx(xl,{place:d,mapsUri:x.mapsUri})}),e.jsx("td",{children:e.jsx(ul,{actions:$})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>c(x.locationName),children:b?"Hide":"Details"})})]}),b&&e.jsx("tr",{className:"bg-zinc-950/35 hover:bg-zinc-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(pl,{location:x,lodging:m,place:d,placeActions:$})})})]},x.id)})})]})})]})}function cl(t){return[{label:"Description",tone:Ct(t.description)?"positive":"neutral",value:Ct(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Ct(t.primaryPhone)?"positive":"neutral",value:Ct(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Ct(t.websiteUri)?"positive":"neutral",value:Ct(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function ll({location:t}){const s=cl(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ie,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function ol({lodging:t}){return e.jsx(pn,{...dl(t)})}function dl(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function xl({place:t,mapsUri:s}){return e.jsx(pn,{...ml(t,s)})}function ml(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function ul({actions:t}){return e.jsx(pn,{...hl(t)})}function hl(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function pn({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ie,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-zinc-600",children:n})]})}function pl({location:t,lodging:s,place:n,placeActions:i}){const a=s?jl(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Vs,{title:"Owner profile · Business Information",children:[e.jsx(Be,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Be,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Be,{label:"Description",value:Ct(t.description)?t.description:"Not returned"}),e.jsx(Be,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Be,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Be,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Be,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Be,{label:"Open status",value:Ti(t.openStatus)}),e.jsx(Be,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Vs,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Be,{label:"Last checked",value:Kn(s.syncedAt)}),e.jsx(Be,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Be,{label:"Populated groups",value:a.length>0?a.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-zinc-500",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(Vs,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Be,{label:"Places tier",value:n.tier}),e.jsx(Be,{label:"Last checked",value:Kn(n.syncedAt)}),e.jsx(Be,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-zinc-500",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-zinc-500 hover:text-zinc-300",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-zinc-800/60 pt-3",children:i.length===0?e.jsx("p",{className:"leading-5 text-zinc-500",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:i.map(c=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-zinc-300",children:[Ls(c.placeActionType),c.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-zinc-600",children:[Ls(c.providerType),c.uri?` · ${bl(c.uri)}`:""]})]},c.placeActionLinkName))})})]})]})}function Vs({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-zinc-500",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Be({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-zinc-600",children:t}),e.jsx("span",{className:"min-w-0 break-words text-zinc-400",children:s})]})}function is(t,s,n){return t===s?"positive":t===0?n:"caution"}function gl(t){switch(t){case"positive":return"text-emerald-300";case"caution":return"text-amber-300";case"negative":return"text-rose-300";case"neutral":return"text-zinc-300"}}function fl(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Ct(t){return typeof t=="string"&&t.trim().length>0}function Ti(t){return t?Ls(t):"Not returned"}function Ls(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function bl(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Kn(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function jl(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&yl(n)).map(([s])=>Ls(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function yl(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function vl({performance:t,freshness:s,timeseries:n}){const i=t.totals,a=Ga.filter(C=>(i[C]??0)>0),c=_a.filter(C=>(i[C]??0)>0),l=Object.keys(i).filter(C=>(i[C]??0)>0&&Ua(C)==="other").sort((C,v)=>(i[v]??0)-(i[C]??0)),p=Object.keys(i).filter(C=>(i[C]??0)===0).sort(),g=n.map(C=>{const v={date:C.date};for(const[k,L]of Object.entries(C.metrics))v[k]=L;return v}),x=n.find(C=>C.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,d=g.length>0,$=s.dataThroughDate?`Data through ${jt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,b=[...a,...l];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),$&&e.jsx("span",{className:"text-[11px] text-zinc-500",children:$})]}),!d||a.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Hn,{data:g,metrics:a,kind:"line",firstPending:x,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:b.map(C=>e.jsxs("span",{className:"text-sm text-zinc-400",children:[$s(C)," ",e.jsx("span",{className:"font-mono text-zinc-100",children:(i[C]??0).toLocaleString()})]},C))})]})]}),d&&c.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Hn,{data:g,metrics:c,kind:"area",firstPending:x,lastDate:m})]}),p.length>0&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Not active: ",p.map(C=>$s(C)).join(", ")]})]})}function Hn({data:t,metrics:s,kind:n,firstPending:i,lastDate:a}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Lt,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ms,{stroke:Es,vertical:!1}),e.jsx(Dt,{dataKey:"date",tick:Ge,tickLine:!1,axisLine:{stroke:et},tickFormatter:$t,minTickGap:24}),e.jsx(Tt,{tick:Ge,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ot,labelFormatter:jt,formatter:(c,l)=>[typeof c=="number"?c.toLocaleString():String(c??0),$s(String(l??""))]}),e.jsx(ji,{wrapperStyle:{fontSize:11,color:Qe.text},formatter:c=>$s(c)}),i&&a&&e.jsx(pc,{x1:i,x2:a,fill:Qe.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Qe.textDim,fontSize:10}}),s.map((c,l)=>n==="line"?e.jsx(Os,{type:"monotone",dataKey:c,stroke:Ue[l%Ue.length],strokeWidth:2,dot:!1,isAnimationActive:!1},c):e.jsx(qt,{type:"monotone",dataKey:c,stackId:"reach",stroke:Ue[l%Ue.length],fill:Ue[l%Ue.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},c))]})})})}function Ys({children:t,label:s="More info",placement:n="top",className:i}){const a=r.useId(),[c,l]=r.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${i??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":c?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:()=>l(!0),onMouseLeave:()=>l(!1),onFocus:()=>l(!0),onBlur:()=>l(!1),children:e.jsx(gc,{className:"h-3.5 w-3.5","aria-hidden":!0})}),c&&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 St=50,Wn={commoncrawl:"Common Crawl","bing-webmaster":"Bing Webmaster"},Nl={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 kt(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function as(t){return t.toLocaleString()}function wl(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function zl(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 Sl(t){const s=t.filter(n=>n.kind===os["backlink-extract"]&&!di(n.status));return s.length===0?null:s.reduce((n,i)=>n.createdAt>i.createdAt?n:i)}function kl(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),c=i%60;return c===0?`${a}m`:`${a}m ${c}s`}function Cl({projectName:t}){const[s,n]=r.useState(null),[i,a]=r.useState("commoncrawl"),[c,l]=r.useState(null),[p,g]=r.useState(null),[x,m]=r.useState([]),[d,$]=r.useState(null),[b,C]=r.useState(null),[v,k]=r.useState("commoncrawl"),[L,R]=r.useState(null),[I,N]=r.useState(Date.now()),[j,u]=r.useState(0),[E,_]=r.useState(!0),[H,T]=r.useState(!1),[z,M]=r.useState(!1),[U,G]=r.useState(null),ne=r.useRef(null),fe=r.useRef(!1),xe=r.useCallback(async()=>{_(!0),G(null);try{const[O,q,ae,le,y,D]=await Promise.all([Qa(t,{excludeCrawlers:!0}).catch(()=>null),Ka().catch(()=>null),Ha(t,{excludeCrawlers:!0,source:i}).catch(()=>null),Wa(t,{limit:St,offset:j,excludeCrawlers:!0,source:i}).catch(Oe=>{if(Oe instanceof cn&&Oe.code==="NOT_FOUND")return null;throw Oe}),Va(t,{source:i}).catch(()=>[]),Ya(t).catch(()=>[])]);n(O),$(q),l(ae),g(le),m(y);const Ce=Sl(D);C(Ce),ne.current=Ce?.id??null}catch(O){G(O instanceof Error?O.message:"Failed to load backlinks")}finally{_(!1)}},[t,j,i]);r.useEffect(()=>{xe()},[xe]),r.useEffect(()=>{if(!s||fe.current)return;const O=s.sources.find(le=>le.hasData),q=s.sources.find(le=>le.connected),ae=O?.source??q?.source;ae&&ae!==i&&a(ae)},[s,i]);function pe(O){fe.current=!0,u(0),a(O)}r.useEffect(()=>{if(!b)return;const O=b.id;let q=!1;const ae=async()=>{try{const y=await xi(O);if(q)return;di(y.status)?(C(null),R(y),await xe()):C(D=>D?.id===y.id?{...D,...y}:D)}catch{}},le=window.setInterval(()=>{ae()},3e3);return()=>{q=!0,window.clearInterval(le)}},[b,xe]),r.useEffect(()=>{if(!b)return;const O=window.setInterval(()=>N(Date.now()),1e3);return()=>window.clearInterval(O)},[b]),r.useEffect(()=>{if(!L||L.status==="failed")return;const O=window.setTimeout(()=>R(null),1e4);return()=>window.clearTimeout(O)},[L]);async function me(){T(!0),G(null);try{const O=await er(t);k("commoncrawl"),C(O),ne.current=O.id}catch(O){O instanceof cn&&O.code==="MISSING_DEPENDENCY"?G("DuckDB is not installed. Visit the Backlinks admin page to install it."):G(O instanceof Error?O.message:"Failed to trigger extract")}finally{T(!1)}}async function he(){M(!0),G(null);try{const O=await Za(t);k("bing-webmaster"),C(O),ne.current=O.id}catch(O){G(O instanceof Error?O.message:"Failed to trigger Bing sync")}finally{M(!1)}}const je=r.useMemo(()=>x.slice().sort((O,q)=>O.queriedAt.localeCompare(q.queriedAt)).map(O=>({date:O.queriedAt,linkingDomains:O.totalLinkingDomains})),[x]),f=p?.rows??[],B=p?.total??0,te=c?.excludedLinkingDomains??0,ce=B>St,de=Math.floor(j/St)+1,ke=Math.max(1,Math.ceil(B/St));return r.useEffect(()=>{j>0&&j>=B&&u(0)},[j,B]),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)."]})]})}),U&&e.jsx(W,{className:"surface-card p-4 mb-4 border-rose-800/60",children:e.jsx("p",{className:"text-sm text-rose-300",children:U})}),b&&e.jsx(W,{className:"surface-card p-4 mb-4 border-sky-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Xa,{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:v==="bing-webmaster"?"Bing sync running":"Extract running"}),e.jsx(ie,{tone:"neutral",children:b.status}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:[kl(b.startedAt??null,b.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",I]})]}),v==="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."]})]})]})}),L&&!b&&e.jsx(W,{className:`surface-card p-4 mb-4 ${L.status==="failed"?"border-rose-800/60":"border-emerald-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[L.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(yi,{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 ${L.status==="failed"?"text-rose-300":"text-emerald-300"}`,children:v==="bing-webmaster"?L.status==="failed"?"Bing sync failed":"Bing sync complete":L.status==="failed"?"Extract failed":"Extract complete"}),L.error?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:Ja(L.error)}):L.status!=="failed"?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:v==="bing-webmaster"?"Inbound links refreshed live from Bing Webmaster.":"Backlinks refreshed from the cached release."}):null]})]})}),A()]});function A(){return E||!s?e.jsx(W,{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:[V(s),i==="bing-webmaster"?be():ye()]})}function V(O){return e.jsx("div",{className:"flex items-center gap-2 mb-4 flex-wrap",role:"tablist","aria-label":"Backlink source",children:O.sources.map(q=>{const ae=q.source===i,le=q.hasData?"bg-emerald-500":q.connected?"bg-amber-500":"bg-zinc-600";return e.jsxs("button",{type:"button",role:"tab","aria-selected":ae,onClick:()=>pe(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 ${ae?"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 ${le}`,"aria-hidden":!0}),Wn[q.source],q.hasData&&e.jsx("span",{className:"text-zinc-500 tabular-nums",children:as(q.totalLinkingDomains)})]},q.source)})})}function Te(){return e.jsx(W,{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(Us,{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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:kt("/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 be(){const O=s?.sources.find(y=>y.source==="bing-webmaster"),q=O?.connected??!1,ae=O?.hasData??!1;return c!==null&&c.totalLinkingDomains>0?X(e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:z||b!==null,onClick:ee(he),children:[e.jsx(rs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Sync running…":z?"Queuing…":"Re-sync Bing"]})):e.jsx(W,{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(Us,{className:"h-5 w-5","aria-hidden":!0})}),e.jsx("div",{className:"flex-1",children:q&&ae?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(P,{type:"button",variant:"outline",size:"sm",disabled:z||b!==null,onClick:ee(he),children:[e.jsx(rs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Sync running…":z?"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(P,{type:"button",size:"sm",disabled:z||b!==null,onClick:ee(he),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Sync running…":z?"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 ye(){const O=c!==null&&c.totalLinkingDomains>0,q=L?.status==="failed",ae=c!==null&&c.totalLinkingDomains===0&&!q,le=d?.status==="ready",y=d?.status==="failed",D=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return O?X(e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:H||b!==null,onClick:ee(me),children:[e.jsx(rs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Extract running…":H?"Queuing…":"Re-run extract"]}),e.jsxs(Ys,{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(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:kt("/backlinks"),children:"Open admin"})})]})):e.jsx(W,{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(Us,{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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:kt("/backlinks"),children:"Set up backlinks"})})})]}),D&&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(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:kt("/backlinks"),children:"View sync status"})})})]}),y&&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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:kt("/backlinks"),children:"Go to Backlinks admin"})})})]}),le&&!D&&!ae&&!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(P,{type:"button",size:"sm",disabled:H||b!==null,onClick:ee(me),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Extract running…":H?"Queuing…":"Run extract"]}),e.jsxs(Ys,{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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:kt("/backlinks"),children:"Go to Backlinks admin"})})})]}),ae&&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:c.release})," found"," ",e.jsx("span",{className:"text-zinc-300",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-zinc-300",children:c.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(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:kt("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:H||b!==null,onClick:ee(me),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Extract running…":H?"Queuing…":"Re-run extract"]}),e.jsxs(Ys,{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:c.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 X(O){if(!c)return null;const q=i==="bing-webmaster",ae=q?"Inbound links":"Linking hosts",le=q?"inbound links":"linking hosts",y=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:as(c.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",c.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",le]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-zinc-50",children:as(c.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",le," 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:wl(c.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",le," 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:Wn[i]})," · ",y," ",e.jsx("code",{className:"text-zinc-400",children:c.release})," · queried ",zl(c.queriedAt),te>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-zinc-500",children:[te," crawler/proxy domain",te===1?"":"s"," hidden"]})]})]}),e.jsx("p",{className:"text-[11px] text-zinc-600 mt-0.5",children:Nl[i]}),je.length>=2&&e.jsxs(W,{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(Pt,{width:"100%",height:"100%",children:e.jsxs(Lt,{data:je,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:Ue[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:Ue[0],stopOpacity:0})]})}),e.jsx(Dt,{dataKey:"date",tick:Ge,stroke:et,tickFormatter:$t}),e.jsx(Tt,{tick:Ge,stroke:et,allowDecimals:!1}),e.jsx(It,{contentStyle:ot.contentStyle,labelStyle:ot.labelStyle,itemStyle:ot.itemStyle,labelFormatter:jt}),e.jsx(qt,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:Ue[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"}),ce&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Page ",de," of ",ke," · ",as(B)," total"]})]}),e.jsx(W,{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:ae})]})}),e.jsxs("tbody",{children:[f.map(D=>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:D.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-zinc-400 tabular-nums",children:as(D.numHosts)})]},D.linkingDomain)),f.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-zinc-500",colSpan:2,children:te>0&&B===0?`Every referring domain in this ${y} was a crawler/proxy host (${te} hidden).`:`No referring domains in this ${y}.`})})]})]})}),ce&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:j===0,onClick:()=>u(D=>Math.max(0,D-St)),children:"Previous"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:j+St>=B,onClick:()=>u(D=>D+St),children:"Next"})]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:O})]})}}function Al({projectName:t}){const s=$e({...tr({client:K,path:{name:t}}),staleTime:hn}),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:c,providersConfigured:l}=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 ",l," engines",e.jsx(Se,{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 ",c," of ",l," engine answers",e.jsx(Se,{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($l,{data:n}),e.jsx(Pl,{data:n}),n.competitorGaps.length>0&&e.jsx(Il,{data:n})]})}function $l({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:i,queriesMentionedOnly:a,queriesInvisible:c}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(zs,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(zs,{label:"Cited only",value:`${i} / ${s}`,helper:"In sources, not named in answer",tone:i>0?"positive-dim":"neutral"}),e.jsx(zs,{label:"Mentioned only",value:`${a} / ${s}`,helper:"Named in answer, no source link",tone:a>0?"caution":"neutral"}),e.jsx(zs,{label:"Invisible",value:`${c} / ${s}`,helper:"No engine cites or mentions",tone:c>0?"negative":"neutral"})]})}function zs({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 Pl({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(Ll,{}),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(Ht,{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(c=>c.provider===i);return e.jsx("td",{className:"text-center",children:a==null?e.jsx(jc,{className:"inline h-3.5 w-3.5 text-zinc-700","aria-label":"no data"}):e.jsx(Dl,{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 Ll(){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(Gt,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gt,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gt,{active:!1,tone:"cited"}),e.jsx(Gt,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Dl({provider:t}){const s=Tl(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Gt,{active:t.cited,tone:"cited"}),e.jsx(Gt,{active:t.mentioned,tone:"mentioned"})]})}function Tl(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 Gt({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 Il({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(Se,{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(Ht,{provider:s.provider})}),e.jsx("td",{className:"text-zinc-300",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Fs="__cited__",Bs="__mentioned__",gt="__mentionShare__";function xn(t){return Math.round(t*1e3)/10}function Rl(t,s,n){const i=t.buckets.length>0,a=t.buckets.length===1;if(n==="overall"){const g=s==="cited"?Fs:Bs,x=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[g]:xn(d[x])})),series:[g],hasData:i,singleBucket:a}}const c=s==="mentioned"?"mentionRate":"citationRate",l=[...new Set(t.buckets.flatMap(g=>Object.keys(g.byProvider??{})))].sort();return{rows:t.buckets.map(g=>{const x={date:g.startDate};for(const m of l){const d=g.byProvider?.[m];x[m]=d?xn(d[c]):null}return x}),series:l,hasData:i,singleBucket:a}}function El(t){const s=t.buckets.map(i=>{const a=i.mentionShare;return{date:i.startDate,[gt]:a?.rate==null?null:xn(a.rate)}}),n=s.map(i=>i[gt]).filter(i=>typeof i=="number"&&Number.isFinite(i));return{rows:s,series:[gt],hasData:n.length>0,singleBucket:n.length===1}}function Ii(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 Vn(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Yn(t){return t>0?`+${t}`:`${t}`}function Ri(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Yn(n.delta)} on ${Vn(n.date)}`).join(", ")}`;const s=[...t].sort((n,i)=>i.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Yn(s.delta)} on ${Vn(s.date)})`}const Ei=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Ml=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Ol=[{value:"mentioned",label:"Mentioned"},{value:"cited",label:"Cited"}],Mi="#18181b",Fl={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Bl(t){return Fl[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Cs(t){return Math.round(t*10)/10}function ql(t){return t===Fs||t===Bs}function Xn(t){return t===Fs?"Cited":t===Bs?"Mentioned":Bl(t)}function Xs(t,s){return t===Fs?bt.positive:t===Bs?Ue[1]:t===gt?bt.positive:xc(t,s)}function Gl(t,s){for(const n of t){const i=n[s];if(typeof i=="number"&&Number.isFinite(i))return i}return null}function Oi(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`