@ainyc/canonry 4.51.2 → 4.51.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +0,0 @@
1
- import{j as e,r as c,L as pt,n as yt,u as Ve,o as Ls,A as On,h as qn}from"./vendor-tanstack-Dq7p98wZ.js";import{c as gs,T as fe,t as Bn,a as Fn,u as tn,C as Gn,b as sn,P as jt,B as z,h as _n,d as Un,e as Qn,f as _e,g as U,i as W,I as $e,j as Nt,k as Kn,l as X,m as Vn,n as Hn,o as Wn,p as Yn,q as nn,r as Xn,s as Jn,S as st,v as Zn,w as ei,x as ti,y as si,z as Is,A as ni,G as Se,D as an,E as ii,F as ai,H as ri,J as ci,K as li,L as re,M as $s,N as rn,O as oi,Q as di,R as xi,U as mi,V as ui,W as hi,X as pi,Y as gi,Z as fi,_ as ji,$ as bi,a0 as ss,a1 as yi,a2 as vi,a3 as Ni,a4 as wi,a5 as zi,a6 as ns,a7 as cn,a8 as ln,a9 as Gt,aa as Si,ab as is,ac as ki,ad as Ci,ae as Ai,af as Di,ag as Li,ah as on,ai as Ii,aj as $i,ak as Ri,al as Pi,am as Ti,an as Ei,ao as Mi,ap as Oi,aq as qi,ar as Bi,as as Fi,at as Gi,au as _i,av as Ui,aw as Qi,ax as Wt,ay as Ki,az as Vi,aA as Rs,aB as Hi,aC as Wi,aD as Yi,aE as Xi,aF as Ji,aG as Zi,aH as dn,aI as ea,aJ as Ps,aK as ta,aL as sa,aM as xn,aN as mn,aO as na,aP as ia,aQ as aa,aR as ra,aS as ca,aT as la,aU as oa,aV as Ts,aW as da,aX as Es,aY as Ms,aZ as xa,a_ as ma,a$ as ua,b0 as ha,b1 as pa,b2 as ga,b3 as un,b4 as hn,b5 as fa,b6 as pn,b7 as ja,b8 as gn,b9 as ba,ba as ya,bb as Tt,bc as va,bd as Na,be as wa,bf as Os}from"./index-VMFHNbas.js";import{R as za}from"./RunRow-NfzAq5p2.js";import{f as as,C as _t,a as mt,b as rs,c as St,d as Ft}from"./ChartPrimitives-9Kx3gzQL.js";import{u as Sa,t as ka,R as cs}from"./server-traffic-Bym-drXr.js";import{R as ls,C as os,X as ds,Y as xs,T as ms,L as Ca,A as zt}from"./vendor-recharts-DWvKDyBF.js";import{C as fn,D as fs,a as Aa,T as Da}from"./trash-2-BNsIoa7t.js";import"./vendor-radix-B57xfQbP.js";import"./vendor-markdown-DK7fbRNb.js";const La=[["path",{d:"M5 12h14",key:"1ays0h"}]],Ia=gs("minus",La);const $a=[["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"}]],Ra=gs("unplug",$a);const Pa=[["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"}]],Ta=gs("upload",Pa),Ea=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function jn(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function bn(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 yn(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(jn).map(bn).filter(Boolean)):new Set}function vn(t,s){const n=jn(t).map(bn).filter(Boolean).filter(i=>!Ea.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function Ma(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Oa(t,s){const n=yn(t);if(s.length<=1||n.size===0)return[...s];const i=new Set,a=[];for(const l of s){if(l.category!=="content"){a.push(l);continue}const o=vn(Ma(l),n);!o||i.has(o)||(i.add(o),a.push(l))}return a}function qa(t){const s=yn(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const l=vn(a.query,s);return!l||i.has(l)?!1:(i.add(l),!0)})}function Yt(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 Ba(t,s){return s<=0?null:Math.round((t-s)/s*100)}function qs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Yt(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Yt(t.prior)} ${s})`:`Flat ${n} (${Yt(t.prior)} ${s})`}function us({state:t,label:s}){return e.jsx(fe,{tone:Fn(t),children:s??Bn(t)})}function Bs({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-zinc-600",children:"No data"});const i={cited:"bg-emerald-400","not-cited":"bg-zinc-600",lost:"bg-rose-400",emerging:"bg-amber-400 ring-1 ring-amber-300/60"},a=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),l=new Date(n[n.length-1].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"});return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:a}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,children:n.map((o,d)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[o.citationState]??"bg-zinc-700"} ${o.model&&d>0&&n[d-1]?.model&&n[d-1].model!==o.model?"ring-1 ring-amber-300/80 ring-offset-1 ring-offset-zinc-950":""}`,title:[o.citationState,new Date(o.createdAt).toLocaleDateString(),o.model?`model ${o.model}`:null,o.model&&d>0&&n[d-1]?.model&&n[d-1].model!==o.model?"model changed":null].filter(Boolean).join(" — ")},d))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:l})]})}function Fa(t){const s=new Map;for(const i of t)for(const a of i.runHistory){const l=s.get(a.createdAt);l?l.states.push(a.citationState):s.set(a.createdAt,{states:[a.citationState],runId:a.runId})}return[...s.entries()].sort(([i],[a])=>i.localeCompare(a)).map(([i,{states:a,runId:l}])=>({runId:l,createdAt:i,citationState:a.includes("cited")?"cited":a.includes("emerging")?"emerging":"not-cited"}))}const Ga=320;function Fs(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 Gs(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 _s(t,s){const n=s==="mentions"?"mentioned":"cited",i=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const a=t[t.length-1].citationState,l=t[t.length-2].citationState;if(l!=="cited"&&a==="cited")return`Newly ${n}`;if(l==="cited"&&a!=="cited")return"Lost since last run";let o=0;for(let d=t.length-1;d>=0&&t[d].citationState===a;d--)o++;return a==="cited"?o<=1?`${i} in latest run`:`${i} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function _a(t,s){return s==="citations"?t:t.map(n=>({...n,citationState:Fs(n,s),runHistory:n.runHistory.map(i=>({...i,citationState:Fs(i,s)}))}))}function Ua({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=tn(),[a,l]=c.useState(new Set),[o,d]=c.useState("mentions"),[h,f]=c.useState(n),p=c.useMemo(()=>{const N=_a(t,o),S=new Map;for(const C of N){const R=C.query,k=s?C.location??null:null,j=s?JSON.stringify([R,k]):R,y=S.get(j)??{key:j,phrase:R,location:k,items:[]};y.items.push(C),S.set(j,y)}return[...S.values()]},[t,o,s]),x=N=>{l(S=>{const C=new Set(S);return C.has(N)?C.delete(N):C.add(N),C})},D=o==="mentions"?"mentioned":"cited",L=o==="mentions"?"Mention History":"Citation History",I=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>d("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>d("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-zinc-500",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200",onClick:()=>{l(N=>N.size===p.length?new Set:new Set(p.map(S=>S.key)))},children:a.size===p.length&&p.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":h==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${h==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>f("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":h==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${h==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>f("detailed"),children:"Detailed"})]})]})]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:L}),e.jsx("th",{children:"Change"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:p.map(({key:N,phrase:S,location:C,items:R})=>{const k=a.has(N),j=R.map(B=>B.citationState),y=j.includes("cited")?"cited":j.includes("emerging")?"emerging":j.includes("lost")?"lost":j.every(B=>B==="pending")?"pending":"not-cited",w=Fa(R),M=R.filter(B=>B.citationState===Gn.cited||B.citationState==="emerging").length,V=_s(w,o);return e.jsxs(c.Fragment,{children:[e.jsxs("tr",{className:"evidence-phrase-row cursor-pointer hover:bg-zinc-800/40",onClick:()=>x(N),"aria-expanded":k,children:[e.jsx("td",{children:e.jsx(sn,{size:14,className:`transition-transform duration-150 text-zinc-500 ${k?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:S}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:C??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:R.map(B=>e.jsx(jt,{provider:B.provider},B.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(us,{state:y,label:Gs(y,o)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${M} of ${R.length} engines ${I}`,children:[M,"/",R.length]})]})}),e.jsx("td",{children:e.jsx(Bs,{history:w})}),e.jsx("td",{className:"evidence-change-cell",children:V}),e.jsx("td",{})]}),k&&R.map(B=>e.jsxs(c.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(jt,{provider:B.provider})}),e.jsx("td",{children:e.jsx(us,{state:B.citationState,label:Gs(B.citationState,o)})}),e.jsx("td",{children:e.jsx(Bs,{history:B.runHistory})}),e.jsx("td",{className:"evidence-change-cell",children:_s(B.runHistory,o)}),e.jsx("td",{children:e.jsx(z,{variant:"ghost",size:"sm",type:"button",onClick:F=>{F.stopPropagation(),i(B.id)},children:"View"})})]}),h==="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(Va,{item:B,onViewFull:()=>i(B.id)})})]})]},B.id))]},N)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",D==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Qa(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const l=Un(a);return l.length>=4?[l]:[]}),...t.recommendedCompetitors??[]].filter(a=>a.trim().length>2),i=[];return s.length>0&&i.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&i.push({terms:n,className:"answer-highlight-competitor"}),i}function Ka(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 Va({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}=Ka(t.answerSnippet,Ga),l=Qa(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:_n(i,l)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-900/60 px-2 py-0.5 text-[11px] text-zinc-300",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-rose-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-rose-900/40 bg-rose-950/30 px-2 py-0.5 text-[11px] text-rose-300",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.competitorDomains.length-4," more"]})]})]}),a&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-emerald-400 hover:text-emerald-300",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Ha({competitors:t,onSelectCompetitor:s,activeFilter:n}){if(t.length===0)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No competitors configured. Add competitors to track overlap."});const i=s!=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"})]})}),e.jsx("tbody",{children:t.map(a=>{const l=n!=null&&n.toLowerCase()===a.domain.toLowerCase(),o=[i?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",l?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:o,onClick:i?()=>s(a.domain):void 0,title:i?`Filter answers to queries where ${a.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-zinc-100",children:a.domain}),e.jsx("td",{children:e.jsx(fe,{tone:Qn(a.pressureLabel),children:a.pressureLabel})}),e.jsx("td",{className:"text-zinc-300 tabular-nums",children:a.totalQueries>0?`${a.citationCount} / ${a.totalQueries}`:"—"}),e.jsx("td",{className:"text-zinc-500 text-xs",children:a.citedQueries.length>0?a.citedQueries.join(", "):"Not cited"})]},a.id)})})]})})}function Us({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:l,coverageValue:o,note:d,updatedAt:h,active:f,onClick:p}){return e.jsxs("button",{type:"button",onClick:p,className:`surface-card w-full text-left transition-colors ${f?"border-zinc-200 bg-zinc-900/50":"hover:border-zinc-700 hover:bg-zinc-900/40"}`,children:[e.jsxs("div",{className:"section-head",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:t}),e.jsx("h3",{children:s})]}),e.jsx(fe,{tone:i,children:n})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:a}),e.jsx("p",{className:"mt-1 truncate text-sm text-zinc-200",children:l})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Coverage"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:o})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1 text-xs text-zinc-500 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{children:d}),e.jsx("span",{children:h?`Updated ${_e(h)}`:"No recent sync yet"})]})]})}function Et({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 Wa=6,bt="__other__",gt="_socialTotal";function Ya(t,s=Wa){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const i=[...n.entries()].sort((p,x)=>x[1]!==p[1]?x[1]-p[1]:p[0].localeCompare(x[0])),a=i.slice(0,s),l=new Set(a.map(([p])=>p)),o=Math.max(0,i.length-s),d=new Map;for(const p of t){let x=d.get(p.date);x||(x={date:p.date,[gt]:0},d.set(p.date,x));const D=l.has(p.source)?p.source:bt;x[D]=(x[D]??0)+p.sessions,x[gt]=(x[gt]??0)+p.sessions}const h=[...d.values()].sort((p,x)=>String(p.date).localeCompare(String(x.date))),f=a.map(([p])=>p);return o>0&&f.push(bt),{data:h,sources:f,otherCount:o}}function ft(t){return t.replace(/\+/g," ")}function Nn(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Xa=["7d","30d","90d","all"],et=Ft,hs="#71717a",wn="#52525b",wt=25;function Mt(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function zn(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 Ja({projectName:t}){const{data:s,isLoading:n,isError:i}=Sa(t);if(n)return e.jsx(U,{className:"p-5",children:e.jsx("div",{className:"text-sm text-zinc-500",children:"Loading server activity…"})});if(i)return e.jsx(U,{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:"Engine crawler hits & AI-referral sessions"}),e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:["Server-side log evidence of bots crawling the site and AI-referral sessions — orthogonal to GA4 click-through traffic below. "," ",e.jsx(pt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Manage sources →"})]})]})}),a.length===0?e.jsx(U,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-zinc-400",children:["No server traffic source connected yet."," ",e.jsx(pt,{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(U,{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 sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:a.map(l=>e.jsxs("tr",{className:"border-t border-zinc-800/60",children:[e.jsx("td",{className:"px-4 py-3 text-zinc-100",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(fe,{tone:ka(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-zinc-400 text-xs",children:l.lastSyncedAt?zn(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(pt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function Za({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Ja,{projectName:t}),e.jsx(er,{projectName:t})]})}function er({projectName:t}){const s=yt(),[n,i]=c.useState(null),[a,l]=c.useState(null),[o,d]=c.useState(!0),[h,f]=c.useState(!1),[p,x]=c.useState(!1),[D,L]=c.useState(null),[I,N]=c.useState(null),[S,C]=c.useState("sessions"),[R,k]=c.useState("desc"),[j,y]=c.useState("sessions"),[w,M]=c.useState("desc"),[V,B]=c.useState("sessions"),[F,A]=c.useState("desc"),[E,q]=c.useState("sessions"),[ee,xe]=c.useState("desc"),[pe,J]=c.useState([]),[_,te]=c.useState([]),[le,oe]=c.useState([]),[u,P]=c.useState(!1),[G,ue]=c.useState("30d");async function he(g){d(!0),L(null);try{const O=await s.fetchQuery({...Kn({client:X,path:{name:t}}),staleTime:Nt});if(g.current)return;if(i(O),!O.connected){l(null),J([]),te([]),oe([]),d(!1);return}const T=G==="all"?void 0:G,[Q,Y,at,ae]=await Promise.all([s.fetchQuery({...Vn({client:X,path:{name:t},query:T?{window:T}:void 0}),staleTime:Nt}).then(Z=>Z),s.fetchQuery({...Hn({client:X,path:{name:t},query:T?{window:T}:void 0}),staleTime:Nt}).catch(()=>[]),s.fetchQuery({...Wn({client:X,path:{name:t},query:T?{window:T}:void 0}),staleTime:Nt}).catch(()=>[]),s.fetchQuery({...Yn({client:X,path:{name:t},query:T?{window:T}:void 0}),staleTime:Nt}).catch(()=>[])]);if(g.current)return;l(Q),J(Y),te(at),oe(ae),d(!1)}catch(O){if(g.current)return;L(O instanceof Error?O.message:"Failed to load GA4 data"),d(!1)}}c.useEffect(()=>{const g={current:!1};return he(g),()=>{g.current=!0}},[t,G,s]);async function ye(){f(!0),L(null),N(null);try{const g=await nn(t);N(`Synced ${g.rowCount.toLocaleString()} page rows, ${g.aiReferralCount.toLocaleString()} AI and ${g.socialReferralCount.toLocaleString()} social referral rows (${g.days} days)`),await s.invalidateQueries({predicate:O=>{const T=O.queryKey[0];return typeof T?._id=="string"&&T._id.startsWith("getApiV1ProjectsByNameGa")}}),await he({current:!1})}catch(g){L(g instanceof Error?g.message:"Sync failed")}finally{f(!1)}}async function se(){x(!0),L(null),N(null);try{await Xn(t),await s.invalidateQueries({predicate:g=>{const O=g.queryKey[0];return typeof O?._id=="string"&&O._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),N("GA4 disconnected")}catch(g){L(g instanceof Error?g.message:"Disconnect failed")}finally{x(!1)}}function ce(g){S===g?k(O=>O==="desc"?"asc":"desc"):(C(g),k("desc"))}function ve(g){j===g?M(O=>O==="desc"?"asc":"desc"):(y(g),M("desc"))}function be(g){V===g?A(O=>O==="desc"?"asc":"desc"):(B(g),A("desc"))}function Ce(g){E===g?xe(O=>O==="desc"?"asc":"desc"):(q(g),xe("desc"))}const Ne=c.useMemo(()=>a?.topPages?[...a.topPages].sort((g,O)=>{const T=g[S],Q=O[S];return typeof T=="string"&&typeof Q=="string"?R==="asc"?T.localeCompare(Q):Q.localeCompare(T):R==="asc"?T-Q:Q-T}):[],[a?.topPages,S,R]),Le=c.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((g,O)=>{const T=g[j],Q=O[j];return typeof T=="string"&&typeof Q=="string"?w==="asc"?T.localeCompare(Q):Q.localeCompare(T):w==="asc"?T-Q:Q-T}):[],[a?.aiReferrals,j,w]),de=c.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((g,O)=>{const T=g[E],Q=O[E];return typeof T=="string"&&typeof Q=="string"?ee==="asc"?T.localeCompare(Q):Q.localeCompare(T):ee==="asc"?T-Q:Q-T}):[],[a?.aiReferralLandingPages,E,ee]),ge=c.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((g,O)=>{const T=g[V],Q=O[V];return typeof T=="string"&&typeof Q=="string"?F==="asc"?T.localeCompare(Q):Q.localeCompare(T):F==="asc"?T-Q:Q-T}):[],[a?.socialReferrals,V,F]),{socialChartData:Ue,socialChartSources:v,socialOtherCount:$}=c.useMemo(()=>{const g=Ya(le);return{socialChartData:g.data,socialChartSources:g.sources,socialOtherCount:g.otherCount}},[le]),{chartData:Te,chartSources:Re,dateRange:De}=c.useMemo(()=>{const g=[...new Set(pe.map(ae=>ae.source))],O=new Map;for(const ae of _)O.set(ae.date,{_totalSessions:ae.sessions,_organicSessions:ae.organicSessions});const T=new Map;for(const ae of pe){const Z=`${ae.date}::${ae.source}`,rt=T.get(Z)??0;T.set(Z,Math.max(rt,ae.sessions))}for(const[ae,Z]of T){const[rt,ct]=ae.split("::");let Fe=O.get(rt);Fe||(Fe={_totalSessions:0,_organicSessions:0},O.set(rt,Fe)),Fe[ct]=(Fe[ct]??0)+Z}const Q=[...O.entries()].sort(([ae],[Z])=>ae.localeCompare(Z)).map(([ae,Z])=>({date:ae,...Z})),Y=Q.map(ae=>ae.date),at=Y.length>0?{start:Y[0],end:Y[Y.length-1]}:null;return{chartData:Q,chartSources:g,dateRange:at}},[pe,_]);if(o&&!n)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return e.jsx(tr,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:g=>{const O=g.queryKey[0];return typeof O?._id=="string"&&O._id.startsWith("getApiV1ProjectsByNameGa")}}),await he({current:!1})))()}});const He=a?.organicSharePctDisplay??"0%",nt=a?.channelBreakdown?.organic.sharePctDisplay??He,Qe=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,it=a?.aiSessionsDeduped??0,Ee=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,We=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",Ye=a?new Set(a.aiReferrals.map(g=>g.source.toLowerCase())).size:0,m=Le[0]??null,H=a?.totalDirectSessions??0,ie=a?.directSharePctDisplay??"0%",je=a?.channelBreakdown?.direct.sessions??H,we=a?.channelBreakdown?.direct.sharePctDisplay??ie,Be=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,Qt=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",Xe=a?.socialSessions??0,Ct=a?.socialSharePctDisplay??"0%",Kt=a?.channelBreakdown?.social.sessions??Xe,vs=a?.channelBreakdown?.social.sharePctDisplay??Ct,At=a?new Set(a.socialReferrals.map(g=>g.source.toLowerCase())).size:0,Pe=ge[0]??null;return e.jsxs(e.Fragment,{children:[D&&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:D}),I&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-emerald-900/20 border border-emerald-800/60 text-sm text-emerald-300",children:I}),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(z,{variant:"outline",size:"sm",disabled:h,onClick:W(ye),children:[e.jsx(cs,{className:`w-3.5 h-3.5 mr-1.5 ${h?"animate-spin":""}`}),h?"Syncing…":"Sync"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:p,onClick:W(se),children:[e.jsx(Ra,{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($e,{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:Xa.map(g=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${G===g?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>ue(g),children:g==="all"?"All":g},g))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Xt,{value:Mt(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Xt,{value:Mt(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${He} of total`,tone:"positive"}),e.jsx(Xt,{value:Mt(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(z,{variant:"outline",size:"sm",disabled:h,onClick:W(ye),children:[e.jsx(cs,{className:`w-3.5 h-3.5 mr-1.5 ${h?"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($e,{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."})]})]}),De&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(De.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(De.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Te.length>0&&e.jsxs(U,{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:Re.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Re.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Re.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(ls,{width:"100%",height:"100%",children:e.jsxs(os,{data:Te,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(ds,{dataKey:"date",tick:mt,tickLine:!1,axisLine:{stroke:_t},tickFormatter:as}),e.jsx(xs,{tick:mt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(ms,{...St,labelFormatter:rs,formatter:(g,O)=>{const T=typeof g=="number"?g.toLocaleString():String(g??0),Q=String(O??"");return Q==="_totalSessions"?[T,"Total Sessions"]:Q==="_organicSessions"?[T,"Organic Sessions"]:[T,Q]}}),e.jsx(Ca,{wrapperStyle:{fontSize:11,color:"#a1a1aa"},formatter:g=>g==="_totalSessions"?"Total Sessions":g==="_organicSessions"?"Organic Sessions":g}),e.jsx(zt,{type:"monotone",dataKey:"_totalSessions",stroke:"#52525b",fill:"#27272a",fillOpacity:.4,strokeWidth:1.5,dot:!1}),Re.map((g,O)=>e.jsx(zt,{type:"monotone",dataKey:g,stackId:"ai",stroke:et[O%et.length],fill:et[O%et.length],fillOpacity:.4,strokeWidth:1.5},g))]})})})]}),e.jsxs(U,{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(Ge,{label:"Organic",value:nt,hint:`${Qe.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(Ge,{label:"Social",value:vs,hint:`${Kt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(Ge,{label:"Direct",value:we,hint:`${je.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(Ge,{label:"Known AI referrers (lower bound)",value:We,hint:`${Ee.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(Ge,{label:"Other channels",value:Qt,hint:`${Be.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."})]}),m&&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:m.source})," via ",m.medium,", accounting for ",m.sessions.toLocaleString()," sessions."]})]}),e.jsxs(U,{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 — sources detected"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.aiReferrals.length>0?`${Ye} 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(Ae,{label:"Source",sortKey:"source",current:j,dir:w,onSort:ve,align:"left"}),e.jsx(Ae,{label:"Medium",sortKey:"medium",current:j,dir:w,onSort:ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ae,{label:"Sessions",sortKey:"sessions",current:j,dir:w,onSort:ve,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ae,{label:"Users",sortKey:"users",current:j,dir:w,onSort:ve,align:"right"})]})}),e.jsx("tbody",{children:Le.map(g=>e.jsx(nr,{referral:g,totalSessions:it},`${g.source}:${g.medium}:${g.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-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(U,{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 — landing pages"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:de.length>0?`${de.length} rows`:"No landing-page rows"})]}),de.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(Ae,{label:"Landing Page",sortKey:"landingPage",current:E,dir:ee,onSort:Ce,align:"left"}),e.jsx(Ae,{label:"Source",sortKey:"source",current:E,dir:ee,onSort:Ce,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ae,{label:"Sessions",sortKey:"sessions",current:E,dir:ee,onSort:Ce,align:"right"}),e.jsx(Ae,{label:"Users",sortKey:"users",current:E,dir:ee,onSort:Ce,align:"right"})]})}),e.jsx("tbody",{children:de.map(g=>e.jsx(ir,{row:g},`${g.landingPage}:${g.source}:${g.medium}:${g.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-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($e,{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."})]})]}),Ue.length>0&&e.jsxs(U,{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"})]}),$>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",v.length-1," sources · ",$," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(ls,{width:"100%",height:"100%",children:e.jsxs(os,{data:Ue,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(ds,{dataKey:"date",tick:mt,tickLine:!1,axisLine:{stroke:_t},tickFormatter:as}),e.jsx(xs,{tick:mt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(ms,{...St,labelFormatter:rs,formatter:(g,O)=>{const T=typeof g=="number"?g.toLocaleString():String(g??0),Q=String(O??"");if(Q===gt)return[T,"Total Social"];if(Q===bt){const Y=`Other (${$} source${$===1?"":"s"})`;return[T,Y]}return[T,ft(Q)]}}),e.jsx(zt,{type:"monotone",dataKey:gt,stroke:wn,fill:"#27272a",fillOpacity:.4,strokeWidth:1.5,dot:!1}),v.map((g,O)=>{const Q=g===bt?hs:et[O%et.length];return e.jsx(zt,{type:"monotone",dataKey:g,stackId:"social",stroke:Q,fill:Q,fillOpacity:.4,strokeWidth:1.5},g)})]})})}),e.jsx(rr,{sources:v,otherCount:$})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(U,{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(Ge,{label:"Social Sessions",value:Mt(Xe),hint:`${Xe.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Ge,{label:"Share of Traffic",value:Ct,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Ge,{label:"Platforms",value:String(At),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."})]}),Pe&&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:`${Pe.source} via ${Pe.medium}`,children:Nn(ft(Pe.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:Pe.medium,children:["via ",ft(Pe.medium)," · ",Pe.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(Ge,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Ge,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Ge,{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(U,{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?ge.length>wt&&!u?`Top ${wt} of ${ge.length}`:`${ge.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(Ae,{label:"Source",sortKey:"source",current:V,dir:F,onSort:be,align:"left"}),e.jsx(Ae,{label:"Medium",sortKey:"medium",current:V,dir:F,onSort:be,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Ae,{label:"Sessions",sortKey:"sessions",current:V,dir:F,onSort:be,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ae,{label:"Users",sortKey:"users",current:V,dir:F,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:(u?ge:ge.slice(0,wt)).map(g=>e.jsx(ar,{referral:g,totalSessions:Xe},`${g.source}:${g.medium}:${g.channelGroup}`))})]})}),ge.length>wt&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>P(g=>!g),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:u?`Show top ${wt}`:`Show all ${ge.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($e,{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(Ae,{label:"Landing Page",sortKey:"landingPage",current:S,dir:R,onSort:ce,align:"left"}),e.jsx(Ae,{label:"Sessions",sortKey:"sessions",current:S,dir:R,onSort:ce,align:"right"}),e.jsx(Ae,{label:"Organic",sortKey:"organicSessions",current:S,dir:R,onSort:ce,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Ae,{label:"Users",sortKey:"users",current:S,dir:R,onSort:ce,align:"right"})]})}),e.jsx("tbody",{children:Ne.map(g=>e.jsx(sr,{page:g},g.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 ${zn(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function tr({projectName:t,onConnected:s}){const[n,i]=c.useState(""),[a,l]=c.useState(null),[o,d]=c.useState(null),[h,f]=c.useState(!1),[p,x]=c.useState(null),D=c.useRef(null),L=c.useCallback(N=>{const S=N.target.files?.[0];if(!S)return;x(null),l(S.name);const C=new FileReader;C.onload=()=>{const R=C.result;try{const k=JSON.parse(R);if(!k.client_email||!k.private_key){x("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),d(null);return}d(R)}catch{x("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),d(null)}},C.onerror=()=>{x("Failed to read file."),d(null)},C.readAsText(S)},[]);async function I(){if(x(null),!n.trim()){x("Property ID is required.");return}if(!o){x("Please upload a service account key file.");return}f(!0);try{await Jn(t,{propertyId:n.trim(),keyJson:o});try{await nn(t)}catch{}s()}catch(N){x(N instanceof Error?N.message:"Failed to connect GA4")}finally{f(!1)}}return e.jsxs(U,{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."}),p&&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:p}),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:N=>i(N.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:D,type:"file",accept:".json,application/json",onChange:L,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>D.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(Ta,{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(z,{variant:"default",size:"sm",disabled:h||!n.trim()||!o,onClick:W(I),children:h?"Connecting & syncing…":"Connect GA4"})]})}function Ae({label:t,sortKey:s,current:n,dir:i,onSort:a,align:l}){const o=n===s;return e.jsxs("th",{className:`py-1 font-medium cursor-pointer select-none hover:text-zinc-300 transition-colors ${l==="right"?"text-right":"text-left"}`,onClick:()=>a(s),children:[t,o&&e.jsx("span",{className:"ml-0.5",children:i==="asc"?"↑":"↓"})]})}const Sn={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function Xt({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 ${Sn[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Ge({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($e,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Sn[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function sr({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 kn={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Cn={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 nr({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=kn[t.sourceDimension]??t.sourceDimension,a=Cn[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 ir({row:t}){const s=kn[t.sourceDimension]??t.sourceDimension,n=Cn[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 ar({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=ft(t.source),l=ft(t.medium);return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 pr-3 text-zinc-200 truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500 truncate",title:t.medium,children:l}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-zinc-700 text-zinc-400",title:`GA4 channel group: ${t.channelGroup}`,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-sky-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function rr({sources:t,otherCount:s}){const n=[{key:gt,color:wn,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===bt)n.push({key:bt,color:hs,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=ft(a);n.push({key:a,color:et[i%et.length]??hs,label:Nn(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-zinc-400",children:n.map(i=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:i.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:i.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:i.label})]},i.key))})}const cr=["7d","30d","90d","all"],Ot=500;function lr({projectName:t,refreshNonce:s}){const n=yt(),[i,a]=c.useState(!1),[l,o]=c.useState([]),[d,h]=c.useState([]),[f,p]=c.useState([]),[x,D]=c.useState(null),[L,I]=c.useState([]),[N,S]=c.useState([]),[C,R]=c.useState(null),[k,j]=c.useState(""),[y,w]=c.useState(""),[M,V]=c.useState("30"),[B,F]=c.useState(!1),[A,E]=c.useState("30d"),[q,ee]=c.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[xe,pe]=c.useState(0),[J,_]=c.useState(!1),[te,le]=c.useState(0),[oe,u]=c.useState(!1),[P,G]=c.useState(""),[ue,he]=c.useState(!0),[ye,se]=c.useState(!1),[ce,ve]=c.useState(!1),[be,Ce]=c.useState(!1),[Ne,Le]=c.useState(!1),[de,ge]=c.useState(!1),[Ue,v]=c.useState(!1),[$,Te]=c.useState(null),[Re,De]=c.useState(!1),[He,nt]=c.useState(!1),[Qe,it]=c.useState(null),[Ee,We]=c.useState(""),[Ye,m]=c.useState(!1),[H,ie]=c.useState(!1),[je,we]=c.useState("indexed"),[Be,Qt]=c.useState(null),Xe=!!(q.query.trim()||q.page.trim()||Be),Ct=Be!==null,Kt=c.useMemo(()=>{if(!Be)return f;const{key:r,dir:b}=Be;return[...f].sort((K,ne)=>{const ze=r===st.CTR?Number.isFinite(K.ctr)?K.ctr:0:K[r],Ie=r===st.CTR?Number.isFinite(ne.ctr)?ne.ctr:0:ne[r];return b==="asc"?ze-Ie:Ie-ze})},[f,Be]),[vs,At]=c.useState([]),[Pe,g]=c.useState(null),[O,T]=c.useState(!1),[Q,Y]=c.useState(null),[at,ae]=c.useState(null),Z=l.find(r=>r.connectionType==="gsc"),rt=f.length>0||L.length>0||N.length>0,ct=Zn(),Fe=ei(),Vt=ti();async function Ns(r){if(!r){h([]),j("");return}ve(!0);try{const{sites:b}=await n.fetchQuery({...ui({client:X,path:{name:t}}),staleTime:Se});h(b),j(r.propertyId??b[0]?.siteUrl??"")}catch(b){h([]),Y(b instanceof Error?b.message:"Failed to load Search Console properties")}finally{ve(!1)}}async function lt(r){Le(!0);const b=r??xe;try{const K=parseInt(q.limit,10)||20,ne=Xe?Ot:K+1,ze=Xe?0:b,Ie={limit:String(ne)};q.startDate&&(Ie.startDate=q.startDate),q.endDate&&(Ie.endDate=q.endDate),q.query&&(Ie.query=q.query),q.page&&(Ie.page=q.page),ze>0&&(Ie.offset=String(ze)),A&&A!=="all"&&!q.startDate&&(Ie.window=A);const Me=await n.fetchQuery({...ii({client:X,path:{name:t},query:Ie}),staleTime:Se});Xe?(_(!1),p(Me),le(Me.length),u(!0)):(_(Me.length>K),p(Me.slice(0,K)),le(0),u(!1))}catch(K){p([]),_(!1),le(0),Y(K instanceof Error?K.message:"Failed to load GSC performance data")}finally{Le(!1)}}async function Ht(){try{const r={};q.startDate&&(r.startDate=q.startDate),q.endDate&&(r.endDate=q.endDate),A&&A!=="all"&&!q.startDate&&(r.window=A);const b=await n.fetchQuery({...ai({client:X,path:{name:t},query:r}),staleTime:Se});D(b)}catch{D(null)}}async function Dt(){ge(!0);try{const r=P.trim()||void 0,b={limit:"20"};r&&(b.url=r);const[K,ne]=await Promise.all([n.fetchQuery({...xi({client:X,path:{name:t},query:b}),staleTime:Se}),n.fetchQuery({...mi({client:X,path:{name:t}}),staleTime:Se})]);I(K),S(ne)}catch(r){I([]),S([]),Y(r instanceof Error?r.message:"Failed to load GSC inspection history")}finally{ge(!1)}}async function ws(){De(!0);try{const[r,b]=await Promise.all([n.fetchQuery({...rn({client:X,path:{name:t}}),staleTime:Se}),n.fetchQuery({...oi({client:X,path:{name:t}}),staleTime:Se}).catch(()=>[])]);Te(r),At(b)}catch(r){Te(null),At([]),Y(r instanceof Error?r.message:"Failed to load coverage data")}finally{De(!1)}}async function zs(r){T(!0),Y(null);try{const b=await $s(t,{urls:r}),{succeeded:K,failed:ne,total:ze}=b.summary;re({title:"Indexing requested",detail:ne===0?`${K} URL${K!==1?"s":""} submitted for indexing.`:`${K}/${ze} submitted successfully, ${ne} failed.`,tone:ne===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(b){Y(b instanceof Error?b.message:"Failed to request indexing")}finally{T(!1)}}async function An(){T(!0),Y(null);try{const r=await $s(t,{urls:[],allUnindexed:!0}),{succeeded:b,failed:K,total:ne}=r.summary;re({title:"Indexing requested",detail:K===0?`${b} unindexed URL${b!==1?"s":""} submitted for indexing.`:`${b}/${ne} submitted successfully, ${K} failed.`,tone:K===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(r){Y(r instanceof Error?r.message:"Failed to request indexing")}finally{T(!1)}}async function Lt(){if(Ee.trim()){m(!0),Y(null);try{await li(t,"gsc",Ee.trim()),await n.invalidateQueries({predicate:r=>{const b=r.queryKey[0];return typeof b?._id=="string"&&b._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(r=>r.map(b=>b.connectionType==="gsc"?{...b,sitemapUrl:Ee.trim()}:b)),re({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),We("")}catch(r){Y(r instanceof Error?r.message:"Failed to save sitemap URL")}finally{m(!1)}}}async function Ss(){Y(null);try{const r=await Fe.mutateAsync({projectName:t,projectLabel:t});it(r.sitemaps),o(b=>b.map(K=>K.connectionType==="gsc"?{...K,sitemapUrl:r.primarySitemapUrl}:K))}catch{}}async function Dn(){nt(!0),Y(null);try{const r=await pi(t);n.setQueryData(gi({client:X,path:{name:t}}),r),it(r.sitemaps),r.sitemaps.length===0&&ae("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(r){Y(r instanceof Error?r.message:"Failed to list sitemaps")}finally{nt(!1)}}async function ks(){he(!0),Y(null);try{const[r,b]=await Promise.all([ni().catch(()=>null),n.fetchQuery({...an({client:X,path:{name:t}}),staleTime:Se}).catch(()=>[])]);a(!!r?.google?.configured),o(b);const K=b.find(ne=>ne.connectionType==="gsc");await Promise.all([Ns(K),lt(),Ht(),Dt(),ws()])}finally{he(!1)}}c.useEffect(()=>{ks()},[t,s]),c.useEffect(()=>{pe(0),lt(0),Ht()},[A]);const Cs=c.useRef(!1);c.useEffect(()=>{if(!Cs.current){Cs.current=!0;return}pe(0),lt(0)},[Ct]);async function Ln(){if(!i){Y("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}se(!0),Y(null),ae(null);try{const{authUrl:r}=await ci(t,"gsc");if(!r.startsWith("https://accounts.google.com/")){Y("Unexpected OAuth redirect URL. Please try again.");return}const b=window.open(r,"_blank","width=600,height=700");if(!b){window.location.assign(r);return}ae("Finish the Google consent flow in the popup, then close it to refresh this project.");const K=window.setInterval(()=>{b.closed&&(window.clearInterval(K),ae(null),n.invalidateQueries({predicate:ne=>{const ze=ne.queryKey[0];return typeof ze?._id=="string"&&ze._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),ks())},1e3)}catch(r){Y(r instanceof Error?r.message:"Failed to start OAuth flow")}finally{se(!1)}}async function In(){Y(null),ae(null);try{await ri(t,"gsc"),await n.invalidateQueries({predicate:r=>{const b=r.queryKey[0];return typeof b?._id=="string"&&b._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(r=>r.filter(b=>b.connectionType!=="gsc")),h([]),j("")}catch(r){Y(r instanceof Error?r.message:"Failed to disconnect")}}async function $n(){if(k){Ce(!0),Y(null);try{await hi(t,"gsc",k),await n.invalidateQueries({predicate:r=>{const b=r.queryKey[0];return typeof b?._id=="string"&&b._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(r=>r.map(b=>b.connectionType==="gsc"?{...b,propertyId:k}:b)),re({title:"GSC property updated",detail:`${t} is now linked to ${k}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(r){Y(r instanceof Error?r.message:"Failed to save GSC property")}finally{Ce(!1)}}}async function Rn(){Y(null),ae(null);try{await ct.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(M,10)||void 0,full:B||void 0}}),await n.invalidateQueries({predicate:r=>{const b=r.queryKey[0];return typeof b?._id=="string"&&b._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function As(){if(y.trim()){v(!0),Y(null),ae(null);try{const r=await di(t,y.trim());await n.invalidateQueries({predicate:b=>{const K=b.queryKey[0];return typeof K?._id=="string"&&K._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),R(r),w(""),await Dt()}catch(r){Y(r instanceof Error?r.message:"Failed to inspect URL")}finally{v(!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"})]})}),Q&&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:[Q,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>Y(null),children:"×"})]}),at&&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:[at,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>ae(null),children:"×"})]}),ue?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Z?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:Z.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",_e(Z.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:W(In),children:"Disconnect"})]}):e.jsxs(U,{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(fe,{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(z,{type:"button",variant:"outline",size:"sm",disabled:ye,onClick:W(Ln),children:ye?"Opening…":"Connect Google Search Console"}):e.jsx(z,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(pt,{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."})]})]})]}),Z&&!Z.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(z,{type:"button",size:"sm",disabled:Fe.isPending||!Z.propertyId,onClick:W(Ss),children:Fe.isPending?"Discovering…":"Auto-discover from GSC"}),e.jsx("span",{className:"self-center text-xs text-amber-400/60",children:"or enter manually:"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-amber-800/40 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-500 focus:border-amber-600 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Ee,onChange:r=>We(r.target.value),onKeyDown:r=>r.key==="Enter"&&void Lt()}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:Ye||!Ee.trim(),onClick:W(Lt),children:Ye?"Saving…":"Save sitemap URL"})]})]})]})]})}),(Z||rt)&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{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:[$&&$.notIndexed.length>0&&e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:O,onClick:()=>{An()},children:O?"Requesting…":`Request indexing (${$.notIndexed.length})`}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Re,onClick:()=>{ws()},children:Re?"Loading…":"Refresh coverage"})]})]}),$&&$.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const r=$.summary.indexed+$.summary.notIndexed,b=r>0?$.summary.indexed/r:0,K=r>0?$.summary.notIndexed/r:0,ne=54,ze=2*Math.PI*ne,Ie=ze*(1-b),Me=ze*K,ot=ze*b;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:ne,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ne,fill:"none",stroke:"#10b981",strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Ie,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),$.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ne,fill:"none",stroke:"#52525b",strokeWidth:"14",strokeDasharray:`${Me} ${ze-Me}`,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:[(b*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:$.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:$.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:["Not indexed",($.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-zinc-600",children:["· ",($.reasonGroups??[]).length," ",($.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),$.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:$.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(r=>{const b=r==="indexed"?$.indexed.length:r==="notIndexed"?$.notIndexed.length:$.deindexed.length,K=r==="indexed"?"Indexed":r==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${je===r?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{we(r),g(null)},children:[K," (",b,")"]},r)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[je==="indexed"&&$.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:$.indexed.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.crawlTime?r.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:r.isMobileFriendly===!0?"Yes":r.isMobileFriendly===!1?"No":"—"})]},r.id))})]}),je==="notIndexed"&&!Pe&&($.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:($.reasonGroups??[]).map(r=>e.jsxs("tr",{className:"cursor-pointer hover:bg-zinc-800/40",onClick:()=>g(r.reason),children:[e.jsx("td",{className:"text-zinc-200",children:r.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:r.count})]},r.reason))})]}),je==="notIndexed"&&!Pe&&($.reasonGroups??[]).length===0&&$.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:$.notIndexed.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.coverageState??"Unknown"})]},r.id))})]}),je==="notIndexed"&&Pe&&(()=>{const r=($.reasonGroups??[]).find(b=>b.reason===Pe);return r?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:()=>g(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:r.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[r.count," affected page",r.count!==1?"s":""]})]}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:O,onClick:()=>{zs(r.urls.map(b=>b.url))},children:O?"Requesting…":`Request indexing (${r.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:r.urls.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:b.url}),e.jsx("td",{className:"text-zinc-400",children:b.crawlTime?b.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:O,onClick:()=>{zs([b.url])},title:"Request indexing",children:"Index"})})]},b.id))})]})]}):null})(),je==="deindexed"&&$.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:$.deindexed.map((r,b)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.previousState}),e.jsx("td",{className:"text-zinc-400",children:r.currentState}),e.jsx("td",{className:"text-zinc-400",children:r.transitionDate.split("T")[0]})]},`${r.url}-${b}`))})]}),(je==="indexed"&&$.indexed.length===0||je==="notIndexed"&&!Pe&&$.notIndexed.length===0||je==="deindexed"&&$.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-zinc-500",children:"No URLs in this category."})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:Re?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(U,{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:cr.map(r=>e.jsx("button",{type:"button",role:"tab","aria-selected":A===r,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${A===r?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>E(r),children:r==="all"?"All":r},r))}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Ne,onClick:()=>{pe(0),lt(0),Ht()},children:Ne?"Loading…":"Apply filters"})]})]}),x&&x.daily.length>0&&(()=>{const r=x.daily,b=Math.max(...r.map(me=>me.impressions),1),{clicks:K,impressions:ne,ctr:ze}=x.totals,Ie=(ze*100).toFixed(1),Me=700,ot=220,Oe={top:12,bottom:36,left:48,right:12},Pn=Me-Oe.left-Oe.right,dt=ot-Oe.top-Oe.bottom,vt=Pn/r.length,It=Math.max(Math.min(vt*.35,24),4),Ds=Math.max(It*.15,1),Tn=me=>{if(me<=0)return 1;const Ke=Math.pow(10,Math.floor(Math.log10(me))),qe=me/Ke,Je=qe<=1.5?1.5:qe<=3?3:qe<=5?5:10;return Math.ceil(Je*Ke)},$t=4,Rt=Math.ceil(Tn(b)/$t)*$t,En=Array.from({length:$t+1},(me,Ke)=>Rt/$t*Ke),Mn=me=>me>=1e3?`${(me/1e3).toFixed(me>=1e4?0:1)}k`:String(me);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:K.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-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Impressions ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:ne.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[Ie,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Me} / ${ot}`},children:e.jsxs("svg",{viewBox:`0 0 ${Me} ${ot}`,className:"h-full w-full",children:[En.map((me,Ke)=>{const qe=Oe.top+dt-me/Rt*dt;return e.jsxs("g",{children:[e.jsx("line",{x1:Oe.left,y1:qe,x2:Me-Oe.right,y2:qe,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:Oe.left-6,y:qe+3.5,textAnchor:"end",fill:"#a1a1aa",fontSize:"10",fontFamily:"inherit",children:Mn(me)})]},`t-${Ke}`)}),r.map((me,Ke)=>{const qe=Oe.left+vt*Ke+vt/2,Je=me.impressions/Rt*dt,Pt=me.clicks/Rt*dt;return e.jsxs("g",{children:[e.jsx("title",{children:`${me.date}
2
- Clicks: ${me.clicks}
3
- Impressions: ${me.impressions}
4
- CTR: ${(me.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:qe-It-Ds/2,y:Oe.top+dt-Je,width:It,height:Math.max(Je,1),rx:2,fill:"#3b82f6",opacity:.85}),e.jsx("rect",{x:qe+Ds/2,y:Oe.top+dt-Pt,width:It,height:Math.max(Pt,1),rx:2,fill:"#10b981",opacity:.85})]},me.date)}),(()=>{const me=Math.min(r.length,7);return Array.from({length:me},(Ke,qe)=>{const Je=r.length===1?0:Math.round(qe/(me-1)*(r.length-1)),Pt=Oe.left+vt*Je+vt/2;return e.jsx("text",{x:Pt,y:ot-8,textAnchor:"middle",fill:"#71717a",fontSize:"10",fontFamily:"inherit",children:r[Je].date.slice(5)},`xl-${Je}`)})})()]})})]})})(),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:q.startDate,onChange:r=>ee(b=>({...b,startDate:r.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:q.endDate,onChange:r=>ee(b=>({...b,endDate:r.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:q.query,onChange:r=>ee(b=>({...b,query:r.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:q.page,onChange:r=>ee(b=>({...b,page:r.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:q.limit,onChange:r=>ee(b=>({...b,limit:r.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 ",Ot.toLocaleString()," matching rows load so sorting covers the full set."]}),f.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(st).map(r=>e.jsx("th",{className:"text-right","aria-sort":Be?.key===r?Be.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:()=>Qt(b=>b?.key===r?b.dir==="desc"?{key:r,dir:"asc"}:null:{key:r,dir:"desc"}),children:[si[r],Be?.key===r?Be.dir==="desc"?" ↓":" ↑":""]})},r))]})}),e.jsx("tbody",{children:Kt.map((r,b)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-400",children:r.date}),e.jsx("td",{className:"max-w-xs truncate text-zinc-200",children:r.query}),e.jsx("td",{className:"max-w-xs truncate text-zinc-400",children:r.page}),e.jsx("td",{className:"text-right tabular-nums text-zinc-300",children:r.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:r.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-400",children:[(Number.isFinite(r.ctr)?r.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:r.position.toFixed(1)})]},`${r.date}:${r.query}:${r.page}:${b}`))})]})}),oe?e.jsx("div",{className:"mt-3 text-xs text-zinc-500",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",te.toLocaleString()," matching row",te===1?"":"s",te>=Ot?` (capped at ${Ot.toLocaleString()} — narrow the filter to see more)`:""]})}):(xe>0||J)&&(()=>{const r=parseInt(q.limit,10)||20,b=xe+1,K=xe+f.length;return e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-zinc-500",children:[e.jsxs("span",{className:"tabular-nums",children:["Showing ",b.toLocaleString()," – ",K.toLocaleString(),J?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Ne||xe===0,onClick:()=>{const ne=Math.max(0,xe-r);pe(ne),lt(ne)},children:"Previous"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Ne||!J,onClick:()=>{const ne=xe+r;pe(ne),lt(ne)},children:"Next"})]})]})})()]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No performance rows match the current filters yet."})]}),e.jsxs(U,{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:y,onChange:r=>w(r.target.value),onKeyDown:r=>r.key==="Enter"&&void As()}),e.jsx(z,{type:"button",size:"sm",disabled:Ue||!Z?.propertyId||!y.trim(),onClick:W(As),children:Ue?"Inspecting…":"Inspect URL"})]}),C&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-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:C.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:C.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:Is(C.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:_e(C.crawlTime)})]})]})]}),e.jsxs(U,{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(z,{type:"button",variant:"outline",size:"sm",disabled:de,onClick:()=>{Dt()},children:de?"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:P,onChange:r=>G(r.target.value)}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:de,onClick:()=>{Dt()},children:"Apply filter"})]}),L.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:L.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-300",children:r.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.coverageState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:Is(r.isMobileFriendly??null)}),e.jsx("td",{className:"text-zinc-400",children:_e(r.inspectedAt)})]},r.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No inspection history yet."})]}),e.jsxs(U,{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"})]})}),N.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:N.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.previousState??"Unknown"}),e.jsx("td",{className:"text-zinc-300",children:r.currentState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:_e(r.transitionDate)})]},`${r.url}:${r.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No deindexed transitions recorded."})]})]}),Z&&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:()=>ie(r=>!r),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 ${H?"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"})]})}),H&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(U,{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:k,disabled:ce||d.length===0,onChange:r=>j(r.target.value),children:d.length===0?e.jsx("option",{value:"",children:ce?"Loading properties…":"No properties available"}):d.map(r=>e.jsxs("option",{value:r.siteUrl,children:[r.siteUrl," · ",r.permissionLevel]},r.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:ce,onClick:()=>{Ns(Z)},children:ce?"Refreshing…":"Refresh properties"}),e.jsx(z,{type:"button",size:"sm",disabled:!k||be,onClick:W($n),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(U,{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:M,onChange:r=>V(r.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:B,onChange:r=>F(r.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(z,{type:"button",size:"sm",disabled:ct.isPending||!Z.propertyId,onClick:W(Rn),children:ct.isPending?"Queueing…":"Queue sync"}),!Z.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property before queueing a sync."})]})]})]}),e.jsxs(U,{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:[Z.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:Z.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:He||!Z.propertyId,onClick:()=>{Dn()},children:He?"Loading…":"Browse sitemaps from GSC"}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:Fe.isPending||!Z.propertyId,onClick:W(Ss),children:Fe.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."}),Qe&&Qe.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 (",Qe.length,")"]}),Qe.map(r=>{const b=r.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:r.path}),r.lastSubmitted&&e.jsxs("p",{className:"text-zinc-500",children:["Submitted: ",r.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[b&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-zinc-300",children:[b.indexed," / ",b.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:()=>We(r.path),children:"Use"})]})]},r.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:Z.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:Ee,onChange:r=>We(r.target.value),onKeyDown:r=>r.key==="Enter"&&Ee.trim()&&void Lt()}),e.jsx(z,{type:"button",size:"sm",disabled:Ye||!Ee.trim(),onClick:W(Lt),children:Ye?"Saving…":Z.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(z,{type:"button",size:"sm",variant:"outline",disabled:Vt.isPending||!Z.propertyId,onClick:W(async()=>{const b=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||Z.sitemapUrl||void 0;Y(null),ae(null);try{await Vt.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:b}})}catch{}}),children:Vt.isPending?"Queueing…":"Inspect sitemap"})]}),!Z.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}function Jt({children:t,label:s="More info",placement:n="top",className:i}){const a=c.useId(),[l,o]=c.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${i??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?a:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-zinc-500 hover:text-zinc-200 focus:text-zinc-200 focus:outline-none focus-visible:ring-1 focus-visible:ring-zinc-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Aa,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&e.jsx("span",{id:a,role:"tooltip",className:`absolute z-50 w-64 rounded border border-zinc-700 bg-zinc-900 px-3 py-2 text-xs font-normal leading-relaxed text-zinc-200 shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const tt=50;function xt(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function qt(t){return t.toLocaleString()}function or(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function dr(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 xr(t){const s=t.filter(n=>n.kind===cn["backlink-extract"]&&!ln(n.status));return s.length===0?null:s.reduce((n,i)=>n.createdAt>i.createdAt?n:i)}function mr(t,s){const n=new Date(t??s).getTime(),i=Math.max(0,Math.floor((Date.now()-n)/1e3));if(i<60)return`${i}s`;const a=Math.floor(i/60),l=i%60;return l===0?`${a}m`:`${a}m ${l}s`}function ur({projectName:t}){const[s,n]=c.useState(null),[i,a]=c.useState(null),[l,o]=c.useState([]),[d,h]=c.useState(null),[f,p]=c.useState(null),[x,D]=c.useState(null),[L,I]=c.useState(Date.now()),[N,S]=c.useState(0),[C,R]=c.useState(!0),[k,j]=c.useState(!1),[y,w]=c.useState(null),M=c.useRef(null),V=c.useCallback(async()=>{R(!0),w(null);try{const[_,te,le,oe,u]=await Promise.all([fi().catch(()=>null),ji(t,{excludeCrawlers:!0}).catch(()=>null),bi(t,{limit:tt,offset:N,excludeCrawlers:!0}).catch(G=>{if(G instanceof ss&&G.code==="NOT_FOUND")return null;throw G}),yi(t).catch(()=>[]),vi(t).catch(()=>[])]);h(_),n(te),a(le),o(oe);const P=xr(u);p(P),M.current=P?.id??null}catch(_){w(_ instanceof Error?_.message:"Failed to load backlinks")}finally{R(!1)}},[t,N]);c.useEffect(()=>{V()},[V]),c.useEffect(()=>{if(!f)return;const _=f.id;let te=!1;const le=async()=>{try{const u=await Gt(_);if(te)return;ln(u.status)?(p(null),D(u),await V()):p(P=>P?.id===u.id?{...P,...u}:P)}catch{}},oe=window.setInterval(()=>{le()},3e3);return()=>{te=!0,window.clearInterval(oe)}},[f,V]),c.useEffect(()=>{if(!f)return;const _=window.setInterval(()=>I(Date.now()),1e3);return()=>window.clearInterval(_)},[f]),c.useEffect(()=>{if(!x||x.status==="failed")return;const _=window.setTimeout(()=>D(null),1e4);return()=>window.clearTimeout(_)},[x]);async function B(){j(!0),w(null);try{const _=await Si(t);p(_),M.current=_.id}catch(_){_ instanceof ss&&_.code==="MISSING_DEPENDENCY"?w("DuckDB is not installed. Visit the Backlinks admin page to install it."):w(_ instanceof Error?_.message:"Failed to trigger extract")}finally{j(!1)}}const F=c.useMemo(()=>l.slice().sort((_,te)=>_.queriedAt.localeCompare(te.queriedAt)).map(_=>({date:_.queriedAt,linkingDomains:_.totalLinkingDomains})),[l]),A=i?.rows??[],E=i?.total??0,q=s?.excludedLinkingDomains??0,ee=E>tt,xe=Math.floor(N/tt)+1,pe=Math.max(1,Math.ceil(E/tt));return c.useEffect(()=>{N>0&&N>=E&&S(0)},[N,E]),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}),", extracted from the Common Crawl hyperlink graph. Updates when a release sync completes — no live scraping, no paid API."]})]})}),y&&e.jsx(U,{className:"surface-card p-4 mb-4 border-rose-800/60",children:e.jsx("p",{className:"text-sm text-rose-300",children:y})}),f&&e.jsx(U,{className:"surface-card p-4 mb-4 border-sky-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ni,{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:"Extract running"}),e.jsx(fe,{tone:"neutral",children:f.status}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:[mr(f.startedAt??null,f.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",L]})]}),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."]})]})]})}),x&&!f&&e.jsx(U,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-rose-800/60":"border-emerald-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.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(fn,{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 ${x.status==="failed"?"text-rose-300":"text-emerald-300"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:wi(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),J()]});function J(){if(C)return e.jsx(U,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading backlinks…"})});const _=s!==null&&s.totalLinkingDomains>0,te=x?.status==="failed",le=s!==null&&s.totalLinkingDomains===0&&!te,oe=d?.status==="ready",u=d?.status==="failed",P=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");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:qt(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Total linking hosts"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-zinc-50",children:qt(s.totalHosts)})}),e.jsx("p",{className:"metric-card-sub",children:"aggregate host count 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:or(s.top10HostsShare)})}),e.jsx("p",{className:"metric-card-sub",children:"share of hosts from the 10 largest linking domains"})]})]}),e.jsxs("p",{className:"text-xs text-zinc-600 mt-2",children:["Release ",e.jsx("code",{className:"text-zinc-400",children:s.release})," · queried ",dr(s.queriedAt),q>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-zinc-500",children:[q," crawler/proxy domain",q===1?"":"s"," hidden"]})]})]}),F.length>=2&&e.jsxs(U,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over releases"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(ls,{width:"100%",height:"100%",children:e.jsxs(os,{data:F,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:Ft[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:Ft[0],stopOpacity:0})]})}),e.jsx(ds,{dataKey:"date",tick:mt,stroke:_t,tickFormatter:as}),e.jsx(xs,{tick:mt,stroke:_t,allowDecimals:!1}),e.jsx(ms,{contentStyle:St.contentStyle,labelStyle:St.labelStyle,itemStyle:St.itemStyle,labelFormatter:rs}),e.jsx(zt,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:Ft[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"}),ee&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Page ",xe," of ",pe," · ",qt(E)," total"]})]}),e.jsx(U,{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:"Linking hosts"})]})}),e.jsxs("tbody",{children:[A.map(G=>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:G.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-zinc-400 tabular-nums",children:qt(G.numHosts)})]},G.linkingDomain)),A.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-zinc-500",colSpan:2,children:q>0&&E===0?`Every referring domain in this release was a crawler/proxy host (${q} hidden).`:"No referring domains in this release."})})]})]})}),ee&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:N===0,onClick:()=>S(G=>Math.max(0,G-tt)),children:"Previous"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:N+tt>=E,onClick:()=>S(G=>G+tt),children:"Next"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:k||f!==null,onClick:W(B),children:[e.jsx(fs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsxs(Jt,{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(z,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:xt("/backlinks"),children:"Open admin"})})]})]}):e.jsx(U,{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(zi,{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(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:xt("/backlinks"),children:"Set up backlinks"})})})]}),P&&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(z,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:xt("/backlinks"),children:"View sync status"})})})]}),u&&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(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:xt("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&!P&&!le&&!te&&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(z,{type:"button",size:"sm",disabled:k||f!==null,onClick:W(B),children:[e.jsx(ns,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Extract running…":k?"Queuing…":"Run extract"]}),e.jsxs(Jt,{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"}),"."]})]})]})]}),te&&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(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:xt("/backlinks"),children:"Go to Backlinks admin"})})})]}),le&&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:s.release})," found"," ",e.jsx("span",{className:"text-zinc-300",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-zinc-300",children:s.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(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:xt("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:k||f!==null,onClick:W(B),children:[e.jsx(ns,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Extract running…":k?"Queuing…":"Re-run extract"]}),e.jsxs(Jt,{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:s.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 hr({projectName:t}){const s=Ve({...ki({client:X,path:{name:t}}),staleTime:is}),n=s.data??null,i=s.error;if(s.isLoading&&!n)return null;if(i)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-rose-400",children:i instanceof Error?i.message:String(i)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-zinc-500",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:a,providersMentioning:l,providersConfigured:o}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",a," of ",o," engines",e.jsx($e,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-zinc-300 flex items-center gap-2",children:["Mentioned in ",l," of ",o," engine answers",e.jsx($e,{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(pr,{data:n}),e.jsx(gr,{data:n}),n.competitorGaps.length>0&&e.jsx(yr,{data:n})]})}function pr({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:i,queriesMentionedOnly:a,queriesInvisible:l}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Bt,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Bt,{label:"Cited only",value:`${i} / ${s}`,helper:"In sources, not named in answer",tone:i>0?"positive-dim":"neutral"}),e.jsx(Bt,{label:"Mentioned only",value:`${a} / ${s}`,helper:"Named in answer, no source link",tone:a>0?"caution":"neutral"}),e.jsx(Bt,{label:"Invisible",value:`${l} / ${s}`,helper:"No engine cites or mentions",tone:l>0?"negative":"neutral"})]})}function Bt({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 gr({data:t}){const s=c.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(fr,{}),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(jt,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-zinc-100",children:n.query}),s.map(i=>{const a=n.providers.find(l=>l.provider===i);return e.jsx("td",{className:"text-center",children:a==null?e.jsx(Ia,{className:"inline h-3.5 w-3.5 text-zinc-700","aria-label":"no data"}):e.jsx(jr,{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 fr(){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(ut,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ut,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ut,{active:!1,tone:"cited"}),e.jsx(ut,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function jr({provider:t}){const s=br(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(ut,{active:t.cited,tone:"cited"}),e.jsx(ut,{active:t.mentioned,tone:"mentioned"})]})}function br(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 ut({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 yr({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($e,{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(jt,{provider:s.provider})}),e.jsx("td",{className:"text-zinc-300",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ps=new Set(["queued","seeding","probing"]);function vr({projectName:t}){const s=yt(),[n,i]=c.useState(null),[a,l]=c.useState(""),[o,d]=c.useState("100"),h=Ve({...Ci({client:X,path:{name:t},query:{limit:"10"}}),refetchInterval:j=>j.state.data?.some(w=>ps.has(w.status))?3e3:!1}),f=h.data??[];c.useEffect(()=>{!n&&f[0]&&i(f[0].id)},[n,f]);const p=f.find(j=>j.id===n)??null,x=Ve({...Ai({client:X,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&ps.has(p.status)?3e3:!1}),D=x.data??null,L=Ve({...Di({client:X,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),I=Ls({mutationFn:()=>{const j={},y=a.trim();y&&(j.icpDescription=y);const w=Number.parseInt(o,10);return Number.isFinite(w)&&w>0&&(j.maxProbes=w),Li(t,j)},onSuccess:async j=>{i(j.sessionId),l(""),await Ks(s,t,j.sessionId),re({title:"Discovery started",detail:`Run ${Zt(j.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${j.sessionId}`,dedupeMode:"replace"})},onError:j=>{re({title:"Discovery failed to start",detail:j instanceof Error?j.message:"Could not start discovery.",tone:"negative"})}}),N=Ls({mutationFn:j=>{if(!n)throw new Error("Select a completed discovery session first.");return Ii(t,n,j)},onSuccess:async j=>{await Ks(s,t,j.sessionId),s.invalidateQueries({queryKey:on({client:X})}),s.invalidateQueries({predicate:y=>Array.isArray(y.queryKey)&&y.queryKey[0]==="projects"&&y.queryKey.length>1}),re({title:"Queries added",detail:Sr(j),tone:"positive",dedupeKey:`discovery:promote:${j.sessionId}`,dedupeMode:"replace"})},onError:j=>{re({title:"Could not add queries",detail:j instanceof Error?j.message:"Could not add queries from this run.",tone:"negative"})}}),S=D??p,C=L.data??null,R=(C?.queriesByBucket.cited.length??0)+(C?.queriesByBucket.aspirational.length??0),k=c.useMemo(()=>(D?.probes??[]).slice(0,30),[D?.probes]);return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Discovery"}),e.jsx("h2",{children:"Find new queries to track"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-500",children:"Describe your ideal customer and Canonry generates the questions they would ask an AI engine, checks which ones already cite your site, then lets you add the promising ones to your tracked queries."})]}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{h.refetch()},children:[e.jsx(cs,{size:14}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(fe,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-zinc-500",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:a,onChange:j=>l(j.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-zinc-500",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",inputMode:"numeric",value:o,onChange:j=>d(j.target.value)}),e.jsx("span",{className:"mt-1 block text-[11px] text-zinc-600",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),e.jsxs(z,{type:"button",size:"sm",disabled:I.isPending,onClick:()=>I.mutate(),children:[e.jsx(ns,{size:14}),I.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),h.isFetching&&e.jsx(fe,{tone:"neutral",children:"Loading"})]}),f.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:f.map(j=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===j.id?"border-zinc-600 bg-zinc-900/70":"border-zinc-800/60 bg-zinc-950/40 hover:border-zinc-700 hover:bg-zinc-900/40"}`,onClick:()=>i(j.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:Zt(j.id)}),e.jsx(fe,{tone:Qs(j.status),children:j.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-[11px] text-zinc-500",children:[e.jsxs("span",{children:["Cited ",j.citedCount??0]}),e.jsxs("span",{children:["Opportunity ",j.aspirationalCount??0]}),e.jsxs("span",{children:["Low value ",j.wastedCount??0]})]})]},j.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:S?Zt(S.id):"No run selected"})]}),S&&e.jsx(fe,{tone:Qs(S.status),children:S.status})]}),S?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ze,{label:"Questions tested",value:S.probeCount??0}),e.jsx(Ze,{label:"Already cited",value:S.citedCount??0,tone:"positive"}),e.jsx(Ze,{label:"Opportunities",value:S.aspirationalCount??0,tone:"caution"}),e.jsx(Ze,{label:"Low value",value:S.wastedCount??0,tone:"negative"})]}),S.error&&e.jsx("div",{className:"rounded-md border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:S.error}),S.icpDescription&&e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-300",children:S.icpDescription})]}),S.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.competitorMap.slice(0,8).map(j=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[j.domain," ",e.jsx("span",{className:"text-zinc-500",children:j.hits})]},j.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),S?.status==="completed"&&e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Add queries to your project"})]}),e.jsxs(z,{type:"button",size:"sm",disabled:N.isPending||R===0,onClick:()=>N.mutate(void 0),children:[e.jsx(fn,{size:14}),N.isPending?"Adding…":"Add recommended queries"]})]}),L.isLoading?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading recommendations…"}):C?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ze,{label:"Queries to add",value:R,tone:"positive"}),e.jsx(Ze,{label:"Already cited",value:C.queriesByBucket.cited.length,tone:"positive"}),e.jsx(Ze,{label:"Opportunities",value:C.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(Ze,{label:"Low value (skipped)",value:C.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-xs leading-5 text-zinc-500",children:"Adding queries starts tracking the “already cited” and “opportunity” questions, plus any competitor sites that kept showing up. “Low value” questions are listed below for reference only and are not added."}),C.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.suggestedCompetitors.map(j=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[j.domain," ",e.jsx("span",{className:"text-zinc-500",children:j.hits})]},j.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"No recommendations available for this run."})]}),e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),x.isFetching&&e.jsx(fe,{tone:"neutral",children:"Loading"})]}),k.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"})]})}),e.jsx("tbody",{children:k.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-zinc-100",children:j.query}),e.jsx("td",{children:e.jsx(fe,{tone:Nr(j.bucket),children:zr(j.bucket)})}),e.jsx("td",{className:"text-zinc-400",children:j.citedDomains.length>0?j.citedDomains.slice(0,3).join(", "):"-"})]},j.id))})]})})]})]})]})]})}function Ze({label:t,value:s,tone:n="neutral"}){const i=n==="positive"?"text-emerald-300":n==="caution"?"text-amber-300":n==="negative"?"text-rose-300":"text-zinc-100";return e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s})]})}function Qs(t){return t==="completed"?"positive":t==="failed"?"negative":ps.has(t)?"caution":"neutral"}function Nr(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const wr={cited:"Already cited",aspirational:"Opportunity","wasted-surface":"Low value"};function zr(t){return t?wr[t]:"Not classified"}function Zt(t){return t.length>8?t.slice(0,8):t}function Sr(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,i=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${i>0?`; ${i} already tracked`:""}.`}async function Ks(t,s,n){await Promise.all([t.invalidateQueries({predicate:i=>{const a=i.queryKey[0];return typeof a?._id=="string"&&a._id.startsWith("getApiV1ProjectsByNameDiscover")}}),t.invalidateQueries({queryKey:$i({client:X})})])}const kr={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function ke(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function Cr(t){if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ar(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Dr({projectName:t}){const[s,n]=c.useState(!1),[i,a]=c.useState(null),l=Ve(Ri({client:X,path:{name:t}}));async function o(){n(!0),a(null);try{await Pi(t,"client")}catch(h){const f=h instanceof ss||h instanceof Error?h.message:"Download failed";a(f)}finally{n(!1)}}if(l.isLoading)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading report…"});if(l.error){const h=l.error instanceof Error?l.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-rose-400",children:h})})}const d=l.data;return d?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:d.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[d.meta.project.canonicalDomain," · ",d.meta.project.country," / ",d.meta.project.language.toUpperCase(),d.meta.location?` · Location: ${Ar(d.meta.location)}`:" · No location set"," · ","Generated ",Cr(d.meta.generatedAt)]}),i&&e.jsx("p",{className:"mt-2 text-xs text-rose-400",children:i})]}),e.jsx("div",{className:"page-header-right",children:e.jsxs(z,{variant:"secondary",size:"sm",onClick:W(o),disabled:s,children:[e.jsx(fs,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})})]}),e.jsx(Er,{report:d}),e.jsx(_r,{report:d,audience:"client"}),e.jsx($r,{report:d}),e.jsx(qr,{report:d,audience:"client",projectName:t}),e.jsx(Br,{report:d})]}):null}const Vs="AI Visibility — Server-Side",Hs="AI engine attention",Lr="What AI engines actually do in your server logs over the last 7 days — the other half of citations.",Ir="Live telemetry from your server logs.";function $r({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kt,{eyebrow:Hs,title:Vs,subtitle:Ir}),e.jsx("p",{className:"text-sm text-zinc-500",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:Ba(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},i=qs(n,"requests"),a=`${ke(s.verifiedCrawlerHits.current)} verified · ${ke(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,l=qs(s.referralArrivals,"sessions"),o=s.byOperator.filter(d=>d.verifiedHits>0||d.unverifiedHits>0||d.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kt,{eyebrow:Hs,title:Vs,subtitle:Lr}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Js,{label:"AI bot requests observed",value:ke(n.current),subtitle:a}),e.jsx(Js,{label:"AI referral sessions",value:ke(s.referralArrivals.current),subtitle:l})]}),o.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"AI tool"}),e.jsx("th",{children:"Bot requests (7d)"}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:o.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:d.operator}),e.jsx("td",{children:ke(d.verifiedHits+d.unverifiedHits)}),e.jsx("td",{children:ke(d.referralArrivals)})]},d.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-zinc-500",children:"Verified requests are reverse-DNS confirmed. Unverified requests are user-agent claims shown separately in agency diagnostics."})]})]})}function Rr(t,s){return t.audience==="both"||t.audience===s}const Pr={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Ut(t){return Pr[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Tr(t){if(!t)return null;const s=t.window??1,n=s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`;return t.direction==="up"?{text:`Up ${t.deltaAbs.toFixed(1)} points ${n}`,tone:"positive",arrow:"↑"}:t.direction==="down"?{text:`Down ${Math.abs(t.deltaAbs).toFixed(1)} points ${n}`,tone:"negative",arrow:"↓"}:{text:`Holding steady ${s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`}`,tone:"neutral",arrow:"→"}}function Er({report:t}){const s=t.executiveSummary,n=t.citationScorecard,i=s.totalQueryCount,a=i>0?`${s.citationRate}%`:"—",l=i>0?`When customers asked AI ${i} ${i===1?"question":"questions"} about your industry, AI linked to your website in ${s.citedQueryCount} of ${i===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer questions about your business.",o=Tr(t.whatsChanged.citationRate),d=n.providers.length>0?n.providers.map(Ut).join(", "):`${ke(s.queryCount)} ${s.queryCount===1?"question":"questions"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-zinc-800/60 bg-zinc-900/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-zinc-50 sm:text-7xl",children:a}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-zinc-300 sm:text-lg",children:l}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-emerald-400":o.tone==="negative"?"text-rose-400":"text-zinc-400"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(es,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:i>0?`Says your name in ${s.mentionedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(es,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:i>0?`Cites your site as a source in ${s.citedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(es,{label:"AI tools tested",value:ke(s.providerCount),subtitle:d})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-semibold text-zinc-200",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-zinc-200",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-zinc-200",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Customer questions we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:["These are the ",n.queries.length," ",n.queries.length===1?"question we asked":"questions we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((h,f)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2 text-sm text-zinc-200",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-zinc-500",children:String(f+1).padStart(2,"0")}),e.jsxs("span",{children:['"',h,'"']})]},f))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"How often each AI tool links to your website"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Higher is better. Each bar shows the share of customer questions where the AI cited your site."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(h=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:Ut(h.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-emerald-500/70",style:{width:`${Math.max(h.citationRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-zinc-100",children:[h.citationRate,"% ",e.jsxs("span",{className:"font-normal text-zinc-500",children:["(",h.citedCount,"/",h.totalCount,")"]})]})]},h.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((h,f)=>e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-2 text-xs text-zinc-400",children:h},f))})]})}function es({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-zinc-50 sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",children:n})]})}function Mr(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Or(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function qr({report:t,audience:s,projectName:n}){const i=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(x=>Rr(x,s)),a=Oa(t,i),l=s==="client",o=Ti(),[d,h]=c.useState(new Set),f=d.size>0?a.filter(x=>!x.targetRef||!d.has(x.targetRef)):a,p=x=>{if(!x.targetRef)return;const D=x.targetRef;h(L=>new Set(L).add(D)),o.mutate({projectName:n,body:{targetRef:D}},{onSuccess:()=>{re({tone:"positive",title:`Dismissed "${x.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:L=>{re({tone:"negative",title:`Couldn't dismiss "${x.title}"`,detail:String(L)}),h(I=>{const N=new Set(I);return N.delete(D),N})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kt,{eyebrow:l?"Action plan":"Agency actions",title:l?"What to do next":"Agency Action Plan",subtitle:l?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),f.length===0?e.jsx(ys,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:f.map((x,D)=>{const L=x.evidence.length>0?x.evidence:x.why,I=x.why.length>0||x.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-zinc-800/80 text-sm font-semibold text-zinc-100",title:"Priority — 1 will move the needle fastest",children:D+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(fe,{tone:Mi(x),children:l?Mr(x.horizon):Ei(x.horizon)}),!l&&e.jsx(fe,{tone:"neutral",children:Oi(x.category)}),e.jsx(fe,{tone:"neutral",children:l?Or(x.confidence):`${qi(x.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-zinc-100",children:x.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-zinc-400",children:x.action}),e.jsx(Ur,{items:L,limit:3,className:"mt-3"}),I&&e.jsxs("details",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("summary",{className:"cursor-pointer text-zinc-500 hover:text-zinc-300",children:l?"See the data behind this":"Evidence details"}),x.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:l?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:x.why.map((N,S)=>e.jsx("li",{children:N},S))})]}),x.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:l?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:x.evidence.map((N,S)=>e.jsx("li",{children:N},S))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-zinc-800/60 pt-3 text-xs text-zinc-300",children:[e.jsx("span",{className:"font-medium",children:l?"What success looks like:":"Win condition:"})," ",x.successMetric]}),x.targetRef&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>p(x),className:"rounded-md border border-zinc-700/60 bg-zinc-900/50 px-2.5 py-1 text-[11px] font-medium text-zinc-300 hover:border-zinc-600 hover:bg-zinc-800/70 hover:text-zinc-100",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${x.priority}-${x.title}`)})})]})}function Ws({label:t,value:s,displayValue:n,max:i,barClass:a}){const l=i>0?Math.max(s/i*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-zinc-300",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a}`,style:{width:`${l}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-zinc-100",children:n})]})}function Br({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,i=t.indexingHealth,a=qa(t).slice(0,5),l=s.length>0?Math.max(...s.map(h=>h.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(h=>h.impressions),1):0,d=s.length>0||n!==null||i!==null||a.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(kt,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),d?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"The websites AI tools cited most often when answering customer questions about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(h=>e.jsx(Ws,{label:h.domain+(h.isCompetitor?" (competitor)":""),value:h.count,displayValue:`${ke(h.count)}×`,max:l,barClass:"bg-zinc-400/70"},h.domain))})]}),i&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${i.indexedPct>=90?"text-emerald-400":i.indexedPct>=70?"text-amber-400":"text-rose-400"}`,children:[i.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[ke(i.indexed)," of ",ke(i.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${i.indexedPct>=90?"bg-emerald-500/70":i.indexedPct>=70?"bg-amber-500/70":"bg-rose-500/70"}`,style:{width:`${Math.max(i.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-medium text-zinc-200",children:ke(i.notIndexed)})," ",i.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ke(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ke(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(h=>e.jsx(Ws,{label:h.query,value:h.impressions,displayValue:`${ke(h.impressions)} ${h.impressions===1?"search":"searches"}`,max:o,barClass:"bg-sky-500/70"},h.query))})]}),a.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Customer questions where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-zinc-300",children:a.map((h,f)=>e.jsxs("li",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-zinc-100",children:h.query}),e.jsx("p",{className:"mt-0.5 text-xs text-zinc-400",children:Bi(h.action)})]},f))})]})]}):e.jsx(ys,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}const Fr=14;function js(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function bs(t){return t==="up"?"↑":t==="down"?"↓":"→"}function ts({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"No prior data"})]});const i=n==="%"?"%":"",a=s.deltaAbs>0?"+":"",l=js(s.direction),o=l==="positive"?"text-emerald-400":l==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,i," ",e.jsx("span",{className:"text-sm font-medium",children:bs(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[a,n==="%"?s.deltaAbs.toFixed(1):s.deltaAbs,i," vs ",s.prior,i]})]})}function Ys({label:t,delta:s,countLabel:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"Not enough trend data"})]});const i=s.deltaAbs>0?"+":"",a=js(s.direction),l=a==="positive"?"text-emerald-400":a==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${l}`,children:[ke(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:bs(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[i,ke(s.deltaAbs)," ",n," vs prior ",Fr," days"]})]})}function Gr({movements:t,audience:s}){const n=t.filter(a=>a.direction!=="flat");if(n.length===0)return null;const i=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:i?"How each AI tool changed":"AI engine movements"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:i?"AI tool":"Engine"}),e.jsx("th",{children:i?"Was":"Prior"}),e.jsx("th",{children:i?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(a=>{const l=a.deltaAbs>0?"+":"",o=js(a.direction),d=o==="positive"?"text-emerald-400":o==="negative"?"text-rose-400":"text-zinc-300";return e.jsxs("tr",{children:[e.jsx("td",{children:i?Ut(a.provider):a.provider}),e.jsxs("td",{children:[a.prior,"%"]}),e.jsxs("td",{children:[a.current,"%"]}),e.jsxs("td",{className:d,children:[l,a.deltaAbs.toFixed(1),"% ",bs(a.direction)]})]},a.provider)})})]})})]})}function Xs({insights:t,heading:s,emptyMessage:n,audience:i}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-zinc-500",children:n})]});const a=i==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!a&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:a?"What changed":"Title"}),e.jsx("th",{children:a?"Customer question":"Query"}),e.jsx("th",{children:a?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[!a&&e.jsxs("td",{children:[e.jsx(fe,{tone:kr[l.severity],children:Fi(l.severity)}),l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[l.title,a&&l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsx("td",{className:"text-xs text-zinc-400",children:l.query}),e.jsx("td",{className:"text-xs text-zinc-400",children:a?Ut(l.provider):l.provider})]},l.id))})]})})]})}function _r({report:t,audience:s}){const n=t.whatsChanged,i=s==="client",a=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,l=e.jsx(kt,{eyebrow:i?"Since last check":"Section 2",title:i?"What's different since last check":"What's Changed",subtitle:i?void 0:n.headline});return a?e.jsxs("section",{className:"page-section-divider",children:[l,e.jsx(ys,{message:i?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[l,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(ts,{label:i?"AI links to your website":"Citation rate",delta:n.citationRate,unit:"%"}),e.jsx(ts,{label:i?"AI mentions your name":"Mention rate",delta:n.mentionRate,unit:"%"}),e.jsx(ts,{label:i?"Questions AI answered with you":"Cited queries",delta:n.citedQueryCount,unit:"count"}),e.jsx(Ys,{label:i?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:i?"visits":"clicks"}),e.jsx(Ys,{label:i?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:i?"visits":"sessions"})]}),e.jsx(Gr,{movements:n.providerMovements,audience:s}),e.jsx(Xs,{insights:n.wins,heading:i?"What got better":"Wins",emptyMessage:i?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(Xs,{insights:n.regressions,heading:i?"What got worse":"Regressions",emptyMessage:i?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function Js({label:t,value:s,tone:n,subtitle:i}){const a=n==="positive"?"text-emerald-400":n==="caution"?"text-amber-400":n==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${a}`,children:s}),i&&e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:i})]})}function kt({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1",children:n})]})}function Ur({items:t,limit:s=3,className:n}){if(t.length===0)return null;const i=t.slice(0,s),a=t.length-i.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[i.map((l,o)=>e.jsx("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-300",children:l},o)),a>0&&e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-400",children:["+",a," more"]})]})}function ys({message:t}){return e.jsx("p",{className:"text-sm text-zinc-500 py-4 text-center",children:t})}function Qr({project:t,onUpdateProject:s,onRefresh:n}){const[i,a]=c.useState(!1),[l,o]=c.useState(!1),[d,h]=c.useState(null),[f,p]=c.useState(t.displayName),[x,D]=c.useState(t.canonicalDomain),[L,I]=c.useState(t.country),[N,S]=c.useState(t.language),[C,R]=c.useState(t.ownedDomains??[]),[k,j]=c.useState(""),[y,w]=c.useState(t.aliases??[]),[M,V]=c.useState(""),[B,F]=c.useState(null),[A,E]=c.useState(!1),[q,ee]=c.useState(!1),[xe,pe]=c.useState(""),[J,_]=c.useState(""),[te,le]=c.useState(""),[oe,u]=c.useState(""),[P,G]=c.useState("");c.useEffect(()=>{i||(p(t.displayName),D(t.canonicalDomain),I(t.country),S(t.language),R(t.ownedDomains??[]),w(t.aliases??[]))},[t,i]);function ue(){a(!1),h(null),p(t.displayName),D(t.canonicalDomain),I(t.country),S(t.language),R(t.ownedDomains??[]),w(t.aliases??[]),j(""),V("")}function he(){const v=k.trim();v&&(C.includes(v)||R([...C,v]),j(""))}function ye(v){R(C.filter($=>$!==v))}function se(){const v=M.trim();if(!v)return;const $=v.toLowerCase();y.some(Te=>Te.toLowerCase()===$)||w([...y,v]),V("")}function ce(v){w(y.filter($=>$!==v))}async function ve(){if(!(!f.trim()||!x.trim()||!L.trim()||!N.trim())){o(!0),h(null);try{await s(t.name,{displayName:f.trim(),canonicalDomain:x.trim(),ownedDomains:C,aliases:y,country:L.trim(),language:N.trim()}),a(!1),re({title:"Project settings saved",detail:`${f.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(v){h(v instanceof Error?v.message:"Failed to save")}finally{o(!1)}}}async function be(){const v=xe.trim(),$=J.trim(),Te=te.trim(),Re=oe.trim();if(!(!v||!$||!Te||!Re)){E(!0),F(null);try{const De={label:v,city:$,region:Te,country:Re};P.trim()&&(De.timezone=P.trim()),await Ui(t.name,De),n(),pe(""),_(""),le(""),u(""),G(""),ee(!1),re({title:"Location added",detail:`${v} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${v}`,dedupeMode:"drop"})}catch(De){F(De instanceof Error?De.message:"Failed to add location")}finally{E(!1)}}}async function Ce(v){E(!0),F(null);try{await _i(t.name,v),n(),re({title:"Location removed",detail:`${v} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${v}`,dedupeMode:"drop"})}catch($){F($ instanceof Error?$.message:"Failed to remove location")}finally{E(!1)}}async function Ne(v){E(!0),F(null);try{await Gi(t.name,v),n(),re({title:"Default location updated",detail:`${v} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch($){F($ instanceof Error?$.message:"Failed to set default location")}finally{E(!1)}}const Le=f!==t.displayName||x!==t.canonicalDomain||L!==t.country||N!==t.language||JSON.stringify(C)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(y)!==JSON.stringify(t.aliases??[]),de="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",ge="block text-xs font-medium text-zinc-400 mb-1",Ue=xe.trim()&&J.trim()&&te.trim()&&oe.trim();return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!i&&e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),d&&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:[d,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>h(null),children:"×"})]}),i?e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:ge,children:"Display name"}),e.jsx("input",{className:de,type:"text",value:f,onChange:v=>p(v.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,children:"Canonical domain"}),e.jsx("input",{className:de,type:"text",value:x,onChange:v=>D(v.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,children:"Country"}),e.jsx("input",{className:de,type:"text",value:L,onChange:v=>I(v.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,children:"Language"}),e.jsx("input",{className:de,type:"text",value:N,onChange:v=>S(v.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:C.map(v=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[v,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>ye(v),"aria-label":`Remove ${v}`,children:"×"})]},v))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${de} flex-1`,type:"text",placeholder:"docs.example.com",value:k,onChange:v=>j(v.target.value),onKeyDown:v=>v.key==="Enter"&&(v.preventDefault(),he())}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:!k.trim(),onClick:he,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,children:"Aliases"}),e.jsx("p",{className:"text-[11px] text-zinc-500 mb-1.5",children:'Additional brand names checked against LLM answer text. Use for product names, prior names, or DBAs (e.g. add "Meta" as an alias to facebook.com).'}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:y.map(v=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[v,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>ce(v),"aria-label":`Remove ${v}`,children:"×"})]},v))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${de} flex-1`,type:"text",placeholder:"Facebook",value:M,onChange:v=>V(v.target.value),onKeyDown:v=>v.key==="Enter"&&(v.preventDefault(),se())}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:!M.trim(),onClick:se,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-zinc-800/60",children:[e.jsx(z,{type:"button",disabled:l||!Le||!f.trim()||!x.trim(),onClick:W(ve),children:l?"Saving...":"Save changes"}),e.jsx(z,{type:"button",variant:"outline",disabled:l,onClick:ue,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(v=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:v},v))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(v=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:v},v))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.country})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[B&&e.jsxs("div",{className:"mb-2 rounded border border-rose-800/40 bg-rose-950/20 px-2 py-1 text-xs text-rose-300",children:[B,e.jsx("button",{type:"button",className:"ml-1 text-rose-400 hover:text-rose-200",onClick:()=>F(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-zinc-600",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(v=>e.jsxs("tr",{className:"border-t border-zinc-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium ${v.label===t.defaultLocation?"border-emerald-700/60 bg-emerald-950/30 text-emerald-300":"border-zinc-700/60 bg-zinc-800/40 text-zinc-300"}`,children:[v.label,v.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:v.city}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:v.region}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:v.country}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500",children:v.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[v.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:A,onClick:()=>{Ne(v.label)},className:"text-[10px] text-zinc-500 hover:text-emerald-400 transition-colors disabled:opacity-40","aria-label":`Set ${v.label} as default location`,children:"Set default"}),e.jsx("button",{type:"button",disabled:A,onClick:()=>{Ce(v.label)},className:"text-[10px] text-zinc-500 hover:text-rose-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${v.label}`,children:"Remove"})]})})]},v.label))})]}):e.jsx("p",{className:"text-zinc-500 text-xs mb-2",children:"No locations configured"}),q?e.jsxs("div",{className:"mt-2 rounded border border-zinc-800 bg-zinc-900/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-zinc-500",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Label *"}),e.jsx("input",{className:de,type:"text",value:xe,onChange:v=>pe(v.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"City *"}),e.jsx("input",{className:de,type:"text",value:J,onChange:v=>_(v.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Region *"}),e.jsx("input",{className:de,type:"text",value:te,onChange:v=>le(v.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Country *"}),e.jsx("input",{className:de,type:"text",value:oe,onChange:v=>u(v.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Timezone (optional)"}),e.jsx("input",{className:de,type:"text",value:P,onChange:v=>G(v.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(z,{type:"button",size:"sm",disabled:A||!Ue,onClick:W(be),children:A?"Adding...":"Add location"}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:A,onClick:()=>{ee(!1),F(null)},children:"Cancel"})]})]}):e.jsx(z,{type:"button",size:"sm",variant:"outline",onClick:()=>ee(!0),children:"+ Add location"})]})]})]})})})]})}const Kr=[{value:"daily",label:"Every day"},{value:"weekly@mon",label:"Every Monday"},{value:"weekly@wed",label:"Every Wednesday"},{value:"weekly@fri",label:"Every Friday"},{value:"twice-daily",label:"Twice a day (6am & 6pm)"},{value:"custom",label:"Custom cron expression"}],Zs=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Vancouver","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Australia/Sydney"];function Vr({projectName:t}){const[s,n]=c.useState("loading"),[i,a]=c.useState(!1),[l,o]=c.useState("daily"),[d,h]=c.useState(6),[f,p]=c.useState(""),[x,D]=c.useState("UTC"),[L,I]=c.useState(!1),[N,S]=c.useState(""),[C,R]=c.useState(!1),[k,j]=c.useState(!1),[y,w]=c.useState(null);c.useEffect(()=>{Qi(t).then(n).catch(()=>n(null))},[t]);const M=()=>{if(s&&s!=="loading"){const A=Vi(s.preset??null,s.cronExpr);o(A.freq),h(A.hour),p(A.customCron);const E=Zs.includes(s.timezone);D(E?s.timezone:"Other"),I(!E),S(E?"":s.timezone)}else o("daily"),h(6),p(""),D("UTC"),I(!1),S("");w(null),a(!0)},V=async()=>{R(!0),w(null);try{const E={timezone:L?N.trim()||"UTC":x};l==="custom"?E.cron=f.trim():E.preset=Wi(l,d);const q=await Rs(t,E);n(q),a(!1),re({title:"Schedule saved",detail:Wt(q.preset??null,q.cronExpr,q.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(A){w(A instanceof Error?A.message:"Failed to save schedule")}finally{R(!1)}},B=async()=>{if(!(!s||s==="loading")){R(!0),w(null);try{const A={timezone:s.timezone,enabled:!s.enabled};s.preset?A.preset=s.preset:A.cron=s.cronExpr;const E=await Rs(t,A);n(E),re({title:E.enabled?"Schedule resumed":"Schedule paused",detail:Wt(E.preset??null,E.cronExpr,E.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(A){w(A instanceof Error?A.message:"Failed to update schedule")}finally{R(!1)}}},F=async()=>{j(!0),w(null);try{await Hi(t),n(null),a(!1),re({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(A){w(A instanceof Error?A.message:"Failed to remove schedule")}finally{j(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),s!=="loading"&&!i&&e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:M,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!i&&s===null&&e.jsx(U,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),s!=="loading"&&!i&&s!==null&&e.jsxs(U,{className:"surface-card compact-card",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:Wt(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(fe,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:C,onClick:W(B),children:s.enabled?"Pause":"Resume"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",disabled:k,onClick:W(F),children:k?"Removing...":"Remove"})]})]}),y&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:y})]}),i&&e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/40 p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:l,onChange:A=>o(A.target.value),children:Kr.map(A=>e.jsx("option",{value:A.value,children:A.label},A.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none disabled:opacity-40",value:d,disabled:l==="twice-daily"||l==="custom",onChange:A=>h(parseInt(A.target.value)),children:Array.from({length:24},(A,E)=>e.jsx("option",{value:E,children:Ki(E)},E))})]})]}),l==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 font-mono focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:f,onChange:A=>p(A.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:L?"Other":x,onChange:A=>{A.target.value==="Other"?(I(!0),D("Other")):(I(!1),D(A.target.value))},children:[Zs.map(A=>e.jsx("option",{value:A,children:A},A)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),L&&e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:N,onChange:A=>S(A.target.value)})]}),y&&e.jsx("p",{className:"text-rose-400 text-sm",children:y}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),w(null)},children:"Cancel"}),e.jsx(z,{type:"button",size:"sm",disabled:C||l==="custom"&&!f.trim(),onClick:W(V),children:C?"Saving...":"Save schedule"})]})]})]})}const Hr=[{value:"citation.lost",label:"Citation lost"},{value:"citation.gained",label:"Citation gained"},{value:"run.completed",label:"Run completed"},{value:"run.failed",label:"Run failed"}];function Wr({projectName:t}){const[s,n]=c.useState("loading"),[i,a]=c.useState(!1),[l,o]=c.useState(""),[d,h]=c.useState(["citation.lost","citation.gained"]),[f,p]=c.useState(!1),[x,D]=c.useState(null),[L,I]=c.useState({}),[N,S]=c.useState(new Set);c.useEffect(()=>{Yi(t).then(n).catch(()=>n([]))},[t]);const C=y=>{h(w=>w.includes(y)?w.filter(M=>M!==y):[...w,y])},R=async()=>{if(!(!l.trim()||d.length===0)){p(!0),D(null);try{const y=await Xi(t,{channel:"webhook",url:l.trim(),events:d});n(w=>w==="loading"?[y]:[...w,y]),o(""),h(["citation.lost","citation.gained"]),a(!1),re({title:"Webhook added",detail:`Notifications will be sent to ${y.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(y){D(y instanceof Error?y.message:"Failed to add webhook")}finally{p(!1)}}},k=async y=>{if(!N.has(y)){S(w=>new Set(w).add(y));try{await Zi(t,y),n(w=>w==="loading"?w:w.filter(M=>M.id!==y)),re({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${y}`,dedupeMode:"drop"})}catch(w){D(w instanceof Error?w.message:"Failed to remove webhook")}finally{S(w=>{const M=new Set(w);return M.delete(y),M})}}},j=async y=>{I(w=>({...w,[y]:{state:"testing"}}));try{const w=await Ji(t,y);I(M=>({...M,[y]:{state:w.ok?"ok":"fail",status:w.status}})),w.ok&&re({title:"Test notification sent",detail:`Webhook returned status ${w.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${y}`,dedupeMode:"replace"})}catch{I(w=>({...w,[y]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),s!=="loading"&&e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!i),D(null)},children:i?"Cancel":"+ Add webhook"})]}),i&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:y=>o(y.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Hr.map(y=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-zinc-600 bg-zinc-800",checked:d.includes(y.value),onChange:()=>C(y.value)}),e.jsx("span",{className:"text-sm text-zinc-300",children:y.label})]},y.value))})]}),x&&e.jsx("p",{className:"text-rose-400 text-sm",children:x}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),D(null)},children:"Cancel"}),e.jsx(z,{type:"button",size:"sm",disabled:f||!l.trim()||d.length===0,onClick:W(R),children:f?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!i&&e.jsx(U,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-zinc-300 break-all",title:y.urlHost,children:y.urlDisplay??y.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:y.events.map(w=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-zinc-700 bg-zinc-800/60 px-2 py-0.5 text-[10px] font-medium text-zinc-400 uppercase tracking-wide",children:w.replace("."," ")},w))})}),e.jsx("td",{children:e.jsx(fe,{tone:y.enabled?"positive":"neutral",children:y.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[L[y.id]&&(()=>{const w=L[y.id],M=w.state==="testing"?"Sending…":w.state==="ok"?`Delivered${w.status?` (${w.status})`:""}`:`Failed${w.status?` (${w.status})`:""}`;return e.jsx(fe,{tone:w.state==="ok"?"positive":w.state==="fail"?"negative":"neutral",children:M})})(),e.jsx(z,{variant:"ghost",size:"sm",type:"button",disabled:L[y.id]?.state==="testing",onClick:()=>{j(y.id)},children:"Test"}),e.jsx(z,{variant:"ghost",size:"sm",type:"button",disabled:N.has(y.id),onClick:()=>{k(y.id)},children:N.has(y.id)?"Removing…":"Remove"})]})})]},y.id))})]}),x&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:x})]})]})}function Yr(t){const s=dn(),n=c.useMemo(()=>!s||!t?null:s.dashboard.projects.find(I=>I.project.name===t)??null,[s,t]),i=Ve({...ea({client:X,path:{name:t??""}}),enabled:!!t&&!n,staleTime:is,refetchOnWindowFocus:"always"}),a=Ve({...ta({client:X,query:{kind:"answer-visibility"}}),enabled:!!t,staleTime:Ps,refetchOnWindowFocus:"always",refetchInterval:I=>I.state.data?.some(C=>C.projectId===i.data?.id&&(C.status==="running"||C.status==="queued"))?3e3:Ps}),l=i.data??null,o=c.useMemo(()=>l?(a.data??[]).filter(I=>I.projectId===l.id):[],[l,a.data]),{latestRunIds:d,previousRunIds:h,latestRunIdsKey:f}=c.useMemo(()=>{const I=o.filter(k=>(k.status==="completed"||k.status==="partial")&&k.kind==="answer-visibility"&&k.trigger!=="probe").sort((k,j)=>j.createdAt.localeCompare(k.createdAt)),N=I[0]?.createdAt??null,S=N?I.filter(k=>k.createdAt===N).map(k=>k.id):[],C=I.find(k=>k.createdAt!==N)?.createdAt??null,R=C?I.filter(k=>k.createdAt===C).map(k=>k.id):[];return{latestRunIds:S,previousRunIds:R,latestRunIdsKey:[...S].sort().join(",")}},[o]),p=Ve({queryKey:["project-dashboard-full",l?.id??null,f||"none"],queryFn:async()=>{if(!l||!t)return null;const[I,N,S,C,R,k,j,y,w]=await Promise.all([sa(t).catch(()=>[]),xn(t).catch(()=>[]),mn(t).catch(()=>[]),d.length?Promise.all(d.map(M=>Gt(M).catch(()=>null))).then(M=>M.filter(V=>V!=null)):Promise.resolve([]),h.length?Promise.all(h.map(M=>Gt(M).catch(()=>null))).then(M=>M.filter(V=>V!=null)):Promise.resolve([]),na(t).catch(()=>null),ia(t).catch(()=>null),aa(t).catch(()=>null),ra(t).catch(()=>null)]);return{project:l,runs:o,queries:I,competitors:N,timeline:S,latestRunDetails:C,previousRunDetails:R,gscCoverage:k,bingCoverage:j,dbInsights:y,overview:w}},enabled:!!l&&!!t&&a.isSuccess,staleTime:is,refetchOnWindowFocus:"always"}),x=c.useMemo(()=>p.data?ca({...p.data,runs:o}):n||null,[p.data,o,n]),D=c.useCallback(async()=>{await Promise.all([i.refetch(),a.refetch(),p.refetch()])},[i.refetch,a.refetch,p.refetch]),L=!x&&(i.isLoading||a.isLoading||p.isLoading);return{commandCenter:x,project:l,isLoading:L,isError:i.isError||a.isError||p.isError,refetch:D}}function ht(t,s){return t.invalidateQueries({predicate:n=>{const i=n.queryKey[0];return typeof i?._id=="string"&&i._id.startsWith(s)}})}function Xr({projectName:t,refreshNonce:s}){const n=yt(),[i,a]=c.useState(null),[l,o]=c.useState([]),[d,h]=c.useState(null),[f,p]=c.useState([]),[x,D]=c.useState([]),[L,I]=c.useState(null),[N,S]=c.useState(""),[C,R]=c.useState(""),[k,j]=c.useState(""),[y,w]=c.useState(!0),[M,V]=c.useState(!1),[B,F]=c.useState(null),[A,E]=c.useState("performance");c.useEffect(()=>{q()},[t,s]);async function q(){w(!0),F(null);try{const u=await n.fetchQuery({...un({client:X,path:{name:t}}),staleTime:Se});if(a(u),u.connected){const[P,G,ue,he]=await Promise.all([n.fetchQuery({...hn({client:X,path:{name:t}}),staleTime:Se}).catch(()=>null),n.fetchQuery({...pn({client:X,path:{name:t}}),staleTime:Se}).catch(()=>[]),n.fetchQuery({...ba({client:X,path:{name:t}}),staleTime:Se}).catch(()=>[]),u.siteUrl?Promise.resolve([]):n.fetchQuery({...ya({client:X,path:{name:t}}),staleTime:Se}).then(ye=>ye.sites).catch(()=>[])]);h(P),p(G),D(ue),o(he)}else h(null),p([]),D([]),o([])}catch(u){F(u instanceof Error?u.message:"Failed to load Bing data")}finally{w(!1)}}async function ee(){if(C.trim()){F(null);try{const u=await va(t,C.trim());await ht(n,"getApiV1ProjectsByNameBing"),R(""),u.availableSites.length>0&&o(u.availableSites),await q()}catch(u){F(u instanceof Error?u.message:"Failed to connect")}}}async function xe(){try{await Na(t),await ht(n,"getApiV1ProjectsByNameBing"),a(null),o([]),h(null),p([]),D([]),I(null),j(""),F(null)}catch(u){F(u instanceof Error?u.message:"Failed to disconnect")}}async function pe(){if(k)try{await wa(t,k),await ht(n,"getApiV1ProjectsByNameBing"),await q()}catch(u){F(u instanceof Error?u.message:"Failed to set site")}}async function J(){if(N.trim())try{const u=await gn(t,N.trim());await ht(n,"getApiV1ProjectsByNameBing"),I(u),p(P=>[u,...P])}catch(u){F(u instanceof Error?u.message:"Inspection failed")}}async function _(u){V(!0),F(null);try{const P=await Os(t,{urls:[u]}),{succeeded:G,failed:ue,total:he}=P.summary;re({title:"Bing submission requested",detail:ue===0?`${G} URL submitted to Bing.`:`${G}/${he} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${u}`,dedupeMode:"replace"})}catch(P){const G=P instanceof Error?P.message:"Submission failed";F(G),re({title:"Bing submission failed",detail:G,tone:"negative",dedupeKey:`bing:indexing:${t}:${u}`,dedupeMode:"replace"})}finally{V(!1)}}async function te(){V(!0),F(null),re({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const u=await Os(t,{allUnindexed:!0}),{succeeded:P,failed:G,total:ue}=u.summary;re({title:"Bing submissions requested",detail:G===0?`${P}/${ue} URL${ue!==1?"s":""} submitted to Bing.`:`${P}/${ue} submitted successfully, ${G} failed.`,tone:G===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(u){const P=u instanceof Error?u.message:"Batch submission failed";F(P),re({title:"Bing submissions failed",detail:P,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{V(!1)}}if(y)return e.jsx(U,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-zinc-400",children:"Loading Bing data..."})});if(!i?.connected)return e.jsxs(U,{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(fe,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-zinc-300",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-zinc-500",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:C,onChange:u=>R(u.target.value),onKeyDown:u=>{u.key==="Enter"&&ee()}}),e.jsx(z,{size:"sm",disabled:!C.trim(),onClick:W(ee),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-zinc-400 hover:text-zinc-300 underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),B&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:B})]});if(!i.siteUrl)return e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{tone:"positive",children:"Connected"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:W(xe),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.domain})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?_e(i.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Select site"}),l.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:k,onChange:u=>j(u.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(u=>e.jsxs("option",{value:u.url,children:[u.url,u.verified?" (verified)":""]},u.url))]}),e.jsx(z,{size:"sm",disabled:!k,onClick:W(pe),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-zinc-500",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),B&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:B})]});const le=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],oe=le.find(u=>u.key===A)??le[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fe,{tone:"positive",children:"Connected"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:W(xe),children:"Disconnect"})]})]}),B&&e.jsx("p",{className:"mb-3 text-xs text-rose-400",children:B}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:["Canonry stores Bing connections per canonical domain. This project is currently mapped to ",e.jsx("code",{children:i.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?_e(i.updatedAt):"—"})]})]})]})]}),e.jsxs(U,{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:oe.eyebrow}),e.jsx("h3",{children:oe.title})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:d?.lastInspectedAt?`Last inspected ${_e(d.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-zinc-800",children:le.map(u=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${A===u.key?"border-zinc-200 text-zinc-200":"border-transparent text-zinc-500 hover:text-zinc-300"}`,onClick:()=>E(u.key),children:u.label},u.key))}),A==="coverage"&&d&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Et,{label:"Indexed",value:d.summary.indexed,tone:"positive"}),e.jsx(Et,{label:"Not in index",value:d.summary.notIndexed+(d.summary.unknown??0),tone:"negative"}),e.jsx(Et,{label:"Status unknown",value:d.summary.unknown??0,tone:"neutral"}),e.jsx(Et,{label:"Coverage",value:`${d.summary.percentage}%`,tone:"neutral"})]}),d.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-zinc-400",children:["Not Indexed (",d.notIndexed.length,")"]}),e.jsx(z,{size:"sm",variant:"ghost",disabled:M,onClick:W(te),children:M?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"HTTP"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:d.notIndexed.map(u=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:u.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:u.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:M,onClick:()=>{_(u.url)},children:"Submit"})})]},u.id))})]})})]}),(d.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-zinc-400",children:["Unknown — not yet confirmed (",(d.unknown??[]).length,")"]}),e.jsx(z,{size:"sm",variant:"ghost",disabled:M,onClick:W(te),children:M?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(d.unknown??[]).map(u=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:u.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:u.lastCrawledDate?_e(u.lastCrawledDate):"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:M,onClick:()=>{_(u.url)},children:"Submit"})})]},u.id))})]})})]}),d.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-zinc-400",children:["Indexed (",d.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:d.indexed.map(u=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:u.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:u.lastCrawledDate?_e(u.lastCrawledDate):"—"})]},u.id))})]})})]})]}),A==="coverage"&&!d&&e.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"No coverage data yet. Inspect URLs to build coverage data."}),A==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"URL to inspect",value:N,onChange:u=>S(u.target.value),onKeyDown:u=>{u.key==="Enter"&&J()}}),e.jsx(z,{size:"sm",disabled:!N.trim(),onClick:W(J),children:"Inspect"})]}),L&&e.jsxs("div",{className:"rounded border border-zinc-800 bg-zinc-900/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-zinc-200",children:L.url}),e.jsxs("div",{className:"text-zinc-400",children:["In Index: ",e.jsx("span",{className:L.inIndex?"text-emerald-400":"text-rose-400",children:L.inIndex?"Yes":"No"})," · ","HTTP: ",L.httpCode??"—"," · ","Crawled: ",L.lastCrawledDate??"—"]})]}),f.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:f.map(u=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:u.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(fe,{tone:u.inIndex?"positive":"negative",children:u.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:u.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:_e(u.inspectedAt)})]},u.id))})]})})]}),A==="performance"&&e.jsx("div",{className:"mt-4",children:x.length===0?e.jsx("p",{className:"text-xs text-zinc-500",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:Tt[st.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:Tt[st.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:Tt[st.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:Tt[st.Position]})]})}),e.jsx("tbody",{children:x.map((u,P)=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:u.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-200",children:u.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:u.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:[(Number.isFinite(u.ctr)?u.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:u.averagePosition.toFixed(1)})]},P))})]})})})]})]})}function Jr({projectName:t}){const s=yt(),[n,i]=c.useState("google"),[a,l]=c.useState(!0),[o,d]=c.useState("idle"),[h,f]=c.useState(null),p=c.useRef(null),[x,D]=c.useState(!1),[L,I]=c.useState(null),[N,S]=c.useState(null),[C,R]=c.useState(!1),[k,j]=c.useState(null),[y,w]=c.useState(null),[M,V]=c.useState(0);async function B(u=!1){u||l(!0),f(null);try{const[P,G,ue]=await Promise.all([s.fetchQuery(ga({client:X})).catch(()=>null),s.fetchQuery({...an({client:X,path:{name:t}}),staleTime:Se}).catch(()=>[]),s.fetchQuery({...un({client:X,path:{name:t}}),staleTime:Se}).catch(()=>null)]),he=G.find(ce=>ce.connectionType==="gsc")??null;D(!!P?.google?.configured),R(!!P?.bing?.configured),I(he),j(ue);const[ye,se]=await Promise.all([he?s.fetchQuery({...rn({client:X,path:{name:t}}),staleTime:Se}).catch(()=>null):Promise.resolve(null),ue?.connected?s.fetchQuery({...hn({client:X,path:{name:t}}),staleTime:Se}).catch(()=>null):Promise.resolve(null)]);S(ye),w(se)}catch(P){f(P instanceof Error?P.message:"Failed to load search console overview")}finally{l(!1)}}async function F(){if(o!=="idle")return;p.current?.abort();const u=new AbortController;p.current=u;const P=u.signal;d("syncing"),f(null);const G=[];try{async function ue(){if(!L)return;const ce=await fa(t);if(!ce?.id)return;const ve=2e3,Ce=Date.now()+12e4;for(;Date.now()<Ce;){if(P.aborted||(await new Promise(Le=>setTimeout(Le,ve)),P.aborted))return;const Ne=await Gt(ce.id).catch(()=>null);if(!Ne)break;if(["completed","failed","cancelled"].includes(Ne.status)){Ne.status!=="completed"&&G.push(`Google sync ${Ne.status}`);break}}}const he=10;async function ye(){if(!k?.connected)return;const ce=await s.fetchQuery({...pn({client:X,path:{name:t}}),staleTime:0}).catch(()=>[]),ve=[...new Set(ce.map(be=>be.url))];if(ve.length===0){await ja(t).catch(()=>null);return}for(let be=0;be<ve.length;be+=he){if(P.aborted)return;const Ce=ve.slice(be,be+he),Le=(await Promise.allSettled(Ce.map(de=>gn(t,de)))).filter(de=>de.status==="rejected").length;Le>0&&G.push(`${Le} Bing inspection(s) failed`)}}const se=await Promise.allSettled([ue(),ye()]);for(const ce of se)ce.status==="rejected"&&G.push(ce.reason instanceof Error?ce.reason.message:"Sync failed");if(P.aborted)return;d("reloading"),await Promise.all([ht(s,"getApiV1ProjectsByNameGoogleGsc"),ht(s,"getApiV1ProjectsByNameBing")]),await B(!0),V(ce=>ce+1),G.length>0&&f(`Partial refresh: ${G.join("; ")}`)}catch(ue){P.aborted||f(ue instanceof Error?ue.message:"Refresh failed")}finally{P.aborted||d("idle")}}c.useEffect(()=>(B(),()=>{p.current?.abort()}),[t]);const A=L?"positive":x?"caution":"negative",E=L?"Connected":x?"Ready to connect":"Needs setup",q=N?`${N.summary.percentage}% indexed`:L?"Awaiting coverage":"No coverage data",ee=N?`${N.summary.notIndexed} not indexed${N.summary.deindexed>0?` · ${N.summary.deindexed} deindexed`:""}`:L?"Run sitemap inspection to populate coverage":x?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",xe=N?.lastSyncedAt??N?.lastInspectedAt??L?.updatedAt??null,pe=k?.connected?"positive":C?"caution":"negative",J=k?.connected?"Connected":C?"Ready to connect":"Needs setup",_=y?`${y.summary.percentage}% indexed`:k?.connected?"Awaiting coverage":"No coverage data",te=y?y.summary.notIndexed+(y.summary.unknown??0):0,le=y?`${te} not in index`:k?.connected?"Inspect URLs to populate coverage":C?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings",oe=y?.lastInspectedAt??k?.updatedAt??null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(U,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search console"}),e.jsx("h2",{children:"Search Engine Intelligence"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-500",children:"Scan both engines at a glance, then open the Google or Bing workspace when you need to inspect coverage or take action."})]}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:a||o!=="idle",onClick:()=>{F()},children:a?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"})]}),h&&e.jsx("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:h}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(Us,{eyebrow:"Google",title:"Google Search Console",status:a?"Loading…":E,tone:a?"neutral":A,targetLabel:"Selected property",targetValue:L?.propertyId??"No property selected",coverageValue:a?"Loading…":q,note:a?"Loading overview…":ee,updatedAt:xe,active:n==="google",onClick:()=>i("google")}),e.jsx(Us,{eyebrow:"Bing",title:"Bing Webmaster Tools",status:a?"Loading…":J,tone:a?"neutral":pe,targetLabel:"Selected site",targetValue:k?.siteUrl??"No site selected",coverageValue:a?"Loading…":_,note:a?"Loading overview…":le,updatedAt:oe,active:n==="bing",onClick:()=>i("bing")})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([u,P])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===u,className:`project-subnav-link ${n===u?"project-subnav-link-active":""}`,onClick:()=>i(u),children:P},u))}),n==="google"&&e.jsx(lr,{projectName:t,refreshNonce:M}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Xr,{projectName:t,refreshNonce:M})]})]})}function Zr({summary:t,onJumpToEvidence:s}){if(!t.hasPreviousRun)return e.jsxs("section",{className:"movement-banner",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),e.jsx("span",{className:"text-zinc-500",children:"First run — no comparison yet"})]});const n=t.gained,i=t.lost,a=n===0&&i===0?"· no changes":n>i?"· improving":i>n?"· declining":"";return e.jsxs("section",{className:"movement-banner",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),n>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-emerald-400 font-medium",onClick:s,title:"Jump to the queries that gained citations",children:["+",n," gained"]}):e.jsx("span",{className:"text-zinc-500",children:"+0 gained"}),e.jsx("span",{className:"text-zinc-700 mx-1",children:"·"}),i>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-rose-400 font-medium",onClick:s,title:"Jump to the queries that lost citations",children:["−",i," lost"]}):e.jsx("span",{className:"text-zinc-500",children:"−0 lost"}),e.jsx("span",{className:"text-zinc-600 ml-2",children:a})]}),t.gainedQueries?.length||t.lostQueries?.length?e.jsxs("div",{className:"movement-banner-detail",children:[t.gainedQueries&&t.gainedQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-emerald-500/90",children:"Gained:"})," ",e.jsx("span",{className:"text-zinc-300",children:en(t.gainedQueries)})]}),t.lostQueries&&t.lostQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-rose-500/90",children:"Lost:"})," ",e.jsx("span",{className:"text-zinc-300",children:en(t.lostQueries)})]})]}):null]})}function en(t,s=4){return t.length<=s?t.map(i=>`"${i}"`).join(", "):`${t.slice(0,s).map(i=>`"${i}"`).join(", ")}, and ${t.length-s} more`}function ec({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const i=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(i===0)return null;const a=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(o=>({label:o.domain,mentions:o.mentionSnapshots,isYou:!1}))].sort((o,d)=>d.mentions-o.mentions),l=a[0]?.mentions??1;return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsx("p",{className:"mention-share-breakdown-title",children:"Mention share breakdown"}),e.jsx("ul",{className:"mention-share-breakdown-rows",children:a.map(o=>{const d=o.mentions/i*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${o.isYou?"text-zinc-100 font-medium":"text-zinc-400"}`,children:o.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${o.isYou?"bg-emerald-500/70":"bg-zinc-500/60"}`,style:{width:`${Math.max(o.mentions/l*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:o.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[d.toFixed(1),"%"]})]},o.label)})})]})}function tc({trend:t,currentScore:s}){if(!t||t.length<2)return e.jsx("span",{className:"text-[11px] text-zinc-600",children:"—"});const n=96,i=24,a=100,l=t.length>1?n/(t.length-1):0,o=t.map((p,x)=>`${(x*l).toFixed(2)},${(i-p/a*i).toFixed(2)}`).join(" "),d=s>=70?"rgb(52 211 153)":s>=40?"rgb(251 191 36)":"rgb(251 113 133)",h=(t.length-1)*l,f=i-t[t.length-1]/a*i;return e.jsxs("svg",{width:n,height:i,viewBox:`0 0 ${n} ${i}`,className:"overflow-visible","aria-label":`Trend ${t.join(", ")}`,role:"img",children:[e.jsx("polyline",{points:o,fill:"none",stroke:d,strokeWidth:1.5,strokeLinejoin:"round",strokeLinecap:"round"}),e.jsx("circle",{cx:h,cy:f,r:2.5,fill:d})]})}const sc={write:{title:"Write or update content",subtitle:"Queries with no answer, persistent gaps, or competitors winning the spot"},investigate:{title:"Investigate what changed",subtitle:"Citations or mentions you lost since the previous run"},monitor:{title:"Keep monitoring",subtitle:"Gains, new providers picking you up, holding ground"}};function nc({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:i}=tn(),[a,l]=c.useState(null),o=s.rows.length>0;if(t.length===0&&!o)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No outstanding opportunities. Trigger a sweep to surface fresh signals."});const d=["write","investigate","monitor"],h=new Map;for(const f of t){const p=h.get(f.actionGroup)??[];p.push(f),h.set(f.actionGroup,p)}return e.jsxs("div",{className:"opportunities-grid",children:[d.map(f=>{const p=h.get(f);if(!p||p.length===0)return null;const x=sc[f];return e.jsxs("div",{className:`opportunity-card opportunity-card-${f}`,children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:x.title}),e.jsx("span",{className:"opportunity-card-count",children:p.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:x.subtitle}),e.jsx("div",{className:"opportunity-card-list",children:p.map(D=>{const L=a===D.id,I=D.affectedPhrases.length>0;return e.jsxs("div",{children:[e.jsx("div",{className:`opportunity-item opportunity-item-${D.tone} ${I?"cursor-pointer":""}`,onClick:I?()=>l(L?null:D.id):void 0,children:e.jsxs("div",{className:"flex items-start gap-1.5 min-w-0",children:[I&&e.jsx(sn,{size:12,className:`mt-1 shrink-0 text-zinc-500 transition-transform duration-150 ${L?"rotate-90":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-100 leading-snug",children:D.title}),D.detail&&e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:D.detail})]})]})}),L&&e.jsx("div",{className:"opportunity-item-detail",children:D.affectedPhrases.map((N,S)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx(us,{state:N.citationState}),e.jsx("span",{className:"text-xs text-zinc-300 truncate",children:N.query}),N.provider&&e.jsx(jt,{provider:N.provider})]}),N.evidenceId&&e.jsx("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 whitespace-nowrap",onClick:C=>{C.stopPropagation(),i(N.evidenceId)},children:"View →"})]},N.evidenceId||`${D.id}-${S}`))})]},D.id)})})]},f)}),o&&e.jsx(ic,{suggestedQueries:s,projectName:n})]})}function ic({suggestedQueries:t,projectName:s}){const n=pa(),[i,a]=c.useState(new Set),l=p=>{a(x=>new Set(x).add(p)),n.mutate({projectName:s,queries:[p]},{onSuccess:()=>{re({tone:"positive",title:`Tracking "${p}"`}),a(x=>{const D=new Set(x);return D.delete(p),D})},onError:x=>{re({tone:"negative",title:`Couldn't add "${p}"`,detail:String(x)}),a(D=>{const L=new Set(D);return L.delete(p),L})}})},{rows:o,totalCandidates:d,skippedAlreadyTracked:h}=t,f=h>0?`GSC queries you're getting impressions for · ${h} already tracked`:"GSC queries you're getting impressions for but aren't tracking yet";return e.jsxs("div",{className:"opportunity-card opportunity-card-track",children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:"Track new queries"}),e.jsx("span",{className:"opportunity-card-count",children:d>o.length?`${o.length} of ${d}`:o.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:f}),e.jsx("div",{className:"opportunity-card-list",children:o.map(p=>{const x=i.has(p.query);return e.jsxs("div",{className:"opportunity-item opportunity-item-neutral flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-100 leading-snug truncate",title:p.query,children:p.query}),e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:p.reason})]}),e.jsx("button",{type:"button",className:"suggested-query-add",disabled:x,onClick:()=>l(p.query),children:x?"Adding…":"+ Track"})]},p.query)})})]})}function pc(t){const{projectId:s}=On({from:"/projects/$projectId"}),i=dn()?.dashboard.projects.find(x=>x.project.id===s)?.project.name??null,a=Ve({...la({client:X}),enabled:!i}),l=i??a.data?.find(x=>x.id===s)?.name??null,{commandCenter:o,isLoading:d,refetch:h}=Yr(l),f=!i&&a.isLoading||d;return!l&&!i&&a.isSuccess&&!d?e.jsx("div",{className:"page-container",children:e.jsxs(U,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project with ID "',s,'".']}),e.jsx(z,{asChild:!0,children:e.jsx(pt,{to:"/",children:"Return to overview"})})]})}):!o||f?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(x=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},x))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(x=>e.jsx("div",{className:"skeleton-text-sm w-full"},x))})]})]}):e.jsx(ac,{model:o,refetch:h,...t})}function ac({tab:t,model:s,refetch:n}){const i=qn(),a=yt(),[l,o]=c.useState(!1),[d,h]=c.useState(!1),[f,p]=c.useState(!1),[x,D]=c.useState(""),[L,I]=c.useState(!1),[N,S]=c.useState(!1),[C,R]=c.useState(""),[k,j]=c.useState(!1),[y,w]=c.useState(!1),[M,V]=c.useState(""),[B,F]=c.useState(!1),[A,E]=c.useState(!1),[q,ee]=c.useState(""),[xe,pe]=c.useState(!1),[J,_]=c.useState(void 0),[te,le]=c.useState(!1),[oe,u]=c.useState(null),[P,G]=c.useState(null),[ue,he]=c.useState(!1),ye=s?.visibilityEvidence??[],se=s?.project.name??"",ce=s?.project.displayName||s?.project.name||se,ve=oa(),be=(s?.recentRuns??[]).some(m=>m.kind===cn["answer-visibility"]&&(m.status===Ts.running||m.status===Ts.queued)),Ce=c.useMemo(()=>(s?.project.locations??[]).map(m=>m.label),[s?.project.locations]),Ne=c.useMemo(()=>new Set(ye.map(m=>m.location??"")),[ye]),Le=Ne.has(""),de=c.useMemo(()=>{const m=[...Ne].filter(Boolean);return m.length>1?m:Ce},[Ne,Ce]);c.useEffect(()=>{if(J===void 0||J===""||!se){G(null),he(!1);return}he(!0),mn(se,J).then(m=>{G(m),he(!1)}).catch(()=>{G(null),he(!1)})},[J,se]);const ge=c.useMemo(()=>{if(!P)return null;const m=new Map;for(const H of P){for(const[ie,je]of Object.entries(H.providerRuns??{}))m.set(`${H.query}::${ie}`,je.map(we=>({runId:we.runId,citationState:we.citationState,createdAt:we.createdAt,answerMentioned:we.answerMentioned,visibilityState:we.visibilityState,visibilityTransition:we.visibilityTransition,mentionState:we.mentionState,mentionTransition:we.mentionTransition})));(!H.providerRuns||Object.keys(H.providerRuns).length===0)&&m.set(`${H.query}::`,H.runs.map(ie=>({runId:ie.runId,citationState:ie.citationState,createdAt:ie.createdAt,answerMentioned:ie.answerMentioned,visibilityState:ie.visibilityState,visibilityTransition:ie.visibilityTransition,mentionState:ie.mentionState,mentionTransition:ie.mentionTransition})))}return m},[P]),Ue=c.useMemo(()=>{let m=J!==void 0?ye.filter(H=>J===""?!H.location:H.location===J):ye;if(oe){const H=oe.toLowerCase();m=m.filter(ie=>ie.competitorDomains.some(je=>je.toLowerCase()===H))}return ge?m.map(H=>{const ie=ge.get(`${H.query}::${H.provider}`)??ge.get(`${H.query}::`);return ie?{...H,runHistory:ie}:H}):m},[ye,J,oe,ge]);async function v(){try{await ve.mutateAsync({projectName:se,projectLabel:ce,sourceAction:"project-run"}),n()}catch{}}async function $(){h(!0);try{await da(se),re({title:"Project deleted",detail:`${ce} was removed.`,tone:"positive",dedupeKey:`project:delete:${se}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(m){console.error("Failed to delete project:",m)}finally{h(!1)}}async function Te(){try{const m=await xa(se),H=typeof m=="string"?m:JSON.stringify(m,null,2),ie=new Blob([H],{type:"text/yaml"}),je=URL.createObjectURL(ie),we=document.createElement("a");we.href=je,we.download=`${se}.yaml`,we.click()}catch(m){re({title:"Export failed",detail:m instanceof Error?m.message:"Could not export project YAML.",tone:"negative"})}}async function Re(){const m=x.split(`
5
- `).map(H=>H.trim()).filter(Boolean);if(m.length!==0){I(!0);try{await ma(se,m),n(),D(""),p(!1)}finally{I(!1)}}}async function De(){const m=C.trim();if(m){j(!0);try{const ie=(await xn(se)).map(we=>we.domain),je=[...new Set([...ie,m])];await ua(se,je),n(),R(""),S(!1)}finally{j(!1)}}}async function He(){const m=M.trim();if(m){F(!0);try{const H=s?.project.ownedDomains??[];await Es(se,[...H,m]),n(),V(""),w(!1)}finally{F(!1)}}}async function nt(m){F(!0);try{const H=s?.project.ownedDomains??[];await Es(se,H.filter(ie=>ie!==m)),n()}finally{F(!1)}}async function Qe(){const m=q.trim();if(m){pe(!0);try{const H=s?.project.aliases??[],ie=m.toLowerCase();if(H.some(je=>je.toLowerCase()===ie)){ee(""),E(!1);return}await Ms(se,[...H,m]),n(),ee(""),E(!1)}finally{pe(!1)}}}async function it(m){pe(!0);try{const H=s?.project.aliases??[];await Ms(se,H.filter(ie=>ie!==m)),n()}finally{pe(!1)}}async function Ee(m,H){await ha(m,H),await a.invalidateQueries({queryKey:on({client:X})})}const We=m=>!Number.isNaN(Number.parseInt(m,10)),Ye=[{key:"overview",label:"Overview",href:`/projects/${s.project.id}`},{key:"search-console",label:"Search Engine Intelligence",href:`/projects/${s.project.id}/search-console`},{key:"activity",label:"Activity",href:`/projects/${s.project.id}/activity`},{key:"report",label:"Report",href:`/projects/${s.project.id}/report`},{key:"backlinks",label:"Backlinks",href:`/projects/${s.project.id}/backlinks`},{key:"discovery",label:"Discovery",href:`/projects/${s.project.id}/discovery`},{key:"settings",label:"Settings",href:`/projects/${s.project.id}/settings`}];return e.jsxs("div",{className:"page-container",children:[l?e.jsxs(U,{className:"surface-card p-6 mb-6 border-rose-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-rose-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-zinc-400 mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-zinc-200",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(z,{type:"button",variant:"destructive",disabled:d,onClick:W($),children:d?"Deleting...":"Yes, delete project"}),e.jsx(z,{type:"button",variant:"outline",disabled:d,onClick:()=>o(!1),children:"Cancel"})]})]}):null,e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain,(s.project.ownedDomains??[]).length===0&&!y&&e.jsx("button",{type:"button",className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-600 hover:text-zinc-400 transition-colors",onClick:()=>w(!0),children:"+ add domain"})," "," · ",s.contextLabel]}),e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map(m=>e.jsx("span",{className:"tag",children:m},m))]}),((s.project.ownedDomains??[]).length>0||y)&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-zinc-500 mr-1",children:"Also tracking"}),(s.project.ownedDomains??[]).map(m=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[m,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",disabled:B,onClick:()=>{nt(m)},"aria-label":`Remove ${m}`,children:"×"})]},m)),y?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-1.5 py-0.5 text-xs text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none w-40",type:"text",placeholder:"docs.example.com",value:M,onChange:m=>V(m.target.value),onKeyDown:m=>{m.key==="Enter"&&He()},autoFocus:!0}),e.jsx(z,{type:"button",size:"sm",disabled:!M.trim()||B,onClick:W(He),children:B?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{w(!1),V("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-zinc-700 px-2 py-0.5 text-[10px] uppercase tracking-wide text-zinc-500 hover:text-zinc-300 hover:border-zinc-500 transition-colors",onClick:()=>w(!0),children:"+ domain"})]}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-zinc-500 mr-1",children:["Also known as",e.jsx($e,{text:"Extra brand names checked against LLM answer text alongside the project name. Use for product names, prior names, or DBAs (e.g. add Meta as an alias to facebook.com). Changing these recomputes mentions on historical runs."})]}),(s.project.aliases??[]).map(m=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[m,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",disabled:xe,onClick:()=>{it(m)},"aria-label":`Remove ${m}`,children:"×"})]},m)),A?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-1.5 py-0.5 text-xs text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none w-40",type:"text",placeholder:"LlamaParse",value:q,onChange:m=>ee(m.target.value),onKeyDown:m=>{m.key==="Enter"&&Qe()},autoFocus:!0}),e.jsx(z,{type:"button",size:"sm",disabled:!q.trim()||xe,onClick:W(Qe),children:xe?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{E(!1),ee("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-zinc-700 px-2 py-0.5 text-[10px] uppercase tracking-wide text-zinc-500 hover:text-zinc-300 hover:border-zinc-500 transition-colors",onClick:()=>E(!0),children:"+ alias"})]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-zinc-500",children:s.dateRangeLabel}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:W(Te),"aria-label":"Export project as YAML",children:e.jsx(fs,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:()=>o(!0),"aria-label":"Delete project",children:e.jsx(Da,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(z,{type:"button",disabled:ve.isPending||be,onClick:W(v),children:ve.isPending?"Starting…":be?"Sweep running…":"Run now"})]})]})]}),e.jsx("nav",{className:"project-subnav","aria-label":"Project sections",children:Ye.map(m=>e.jsx(pt,{to:m.href,className:`project-subnav-link ${m.key===t?"project-subnav-link-active":""}`,"aria-current":m.key===t?"page":void 0,children:m.label},m.key))}),t==="overview"?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"aeo-hero",children:[e.jsx("p",{className:"aeo-hero-title",children:"AEO performance"}),e.jsx("div",{className:"aeo-hero-rows",children:[{key:"mention",label:"Mentioned",tooltip:"Your domain or company name was in the answer returned by the LLM.",summary:s.mentionSummary},{key:"citation",label:"Cited",tooltip:"An LLM used a page on your domain as a source for its answer.",summary:s.visibilitySummary},{key:"mention-share",label:"Mention share",tooltip:"Of all brand mentions in answer text across your tracked queries (you + tracked competitors), the % that were you. Head-to-head AI prominence, not market share.",summary:s.mentionShareSummary}].map(m=>e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("div",{className:"aeo-hero-row-label",children:[e.jsx("span",{children:m.label}),e.jsx($e,{text:m.tooltip})]}),e.jsxs("div",{className:"aeo-hero-row-value",children:[e.jsx("span",{className:"text-zinc-50",children:m.summary.value}),We(m.summary.value)?e.jsx("span",{className:"text-zinc-600",children:"%"}):null]}),e.jsx("div",{className:"aeo-hero-row-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${m.summary.tone}`,style:{width:m.summary.progress!==void 0?`${Math.min(Math.max(m.summary.progress,0),100)}%`:"0%"}})}),e.jsx("div",{className:"aeo-hero-row-detail",children:m.summary.delta})]},m.key))}),e.jsx(ec,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name}),s.providerScores.length>0&&e.jsxs("p",{className:"aeo-hero-context",children:["Across ",s.providerScores.length," ",s.providerScores.length===1?"provider":"providers","."]})]}),e.jsx(Zr,{summary:s.movementSummary,onJumpToEvidence:()=>document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})}),e.jsxs("section",{className:"metric-grid",children:[e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Mention Gaps",e.jsx($e,{text:"Queries where a competitor was mentioned in the answer but your brand wasn't."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-zinc-600",children:[" / ",s.queryCounts.total]})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.mentionGaps.tone}`,style:{width:s.mentionGaps.progress!==void 0?`${Math.min(Math.max(s.mentionGaps.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.mentionGaps.delta})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Citation Gaps",e.jsx($e,{text:"Queries where a competitor was cited as a source but you weren't."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.gapQueries.value}),e.jsxs("span",{className:"text-zinc-600",children:[" / ",s.queryCounts.total]})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.gapQueries.tone}`,style:{width:s.gapQueries.progress!==void 0?`${Math.min(Math.max(s.gapQueries.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.gapQueries.delta})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Index Coverage",e.jsx($e,{text:"Percentage of your tracked URLs that Google or Bing has indexed."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.indexCoverage.value}),e.jsx("span",{className:"text-zinc-600",children:"%"})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.indexCoverage.tone}`,style:{width:`${Number.parseInt(s.indexCoverage.value,10)||0}%`}})}),e.jsx("p",{className:"metric-card-detail",children:s.indexCoverage.delta})]})]}),e.jsxs("section",{id:"evidence-section",className:"page-section-divider scroll-mt-24",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Answer evidence"}),e.jsx("h2",{children:"What the LLMs said"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[new Set(s.visibilityEvidence.map(m=>m.query)).size," queries tracked"]}),e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>p(!f),children:f?"Cancel":"+ Add queries"})]})]}),f&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3",children:[e.jsx("textarea",{className:"w-full resize-none 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",rows:3,placeholder:"Enter queries, one per line",value:x,onChange:m=>D(m.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-zinc-500",children:[x.split(`
6
- `).filter(m=>m.trim()).length," queries"]}),e.jsx(z,{type:"button",size:"sm",disabled:!x.trim()||L,onClick:W(Re),children:L?"Adding...":"Add queries"})]})]}),s.project.locations&&s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${J===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":J===void 0,onClick:()=>{_(void 0)},children:"All locations"}),s.project.locations.map(m=>e.jsx("button",{className:`filter-chip ${J===m.label?"filter-chip-active":""}`,type:"button","aria-pressed":J===m.label,onClick:()=>{_(m.label),le(!1)},children:m.label},m.label)),Le&&e.jsx("button",{className:`filter-chip ${J===""?"filter-chip-active":""}`,type:"button","aria-pressed":J==="",onClick:()=>{_(""),le(!1)},children:"No location"}),de.length>1&&J===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${te?"filter-chip-active":""}`,type:"button","aria-pressed":te,onClick:()=>le(m=>!m),title:"Side-by-side location comparison",children:"Compare"})]}),oe&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-rose-900/40 bg-rose-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-rose-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-zinc-200",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:oe})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-zinc-400 hover:text-zinc-200",onClick:()=>u(null),children:"Clear filter ×"})]}),e.jsx(Ua,{evidence:Ue,compareLocations:te})]}),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:"Opportunities"}),e.jsx("h2",{children:"What to act on next"})]})}),e.jsx(nc,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:se})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitors"}),e.jsx("h2",{children:"Competitive landscape"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>S(!N),children:N?"Cancel":"+ Add competitor"})]})]}),N&&e.jsxs("div",{className:"mb-3 flex gap-2 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3",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:"competitor.com",value:C,onChange:m=>R(m.target.value),onKeyDown:m=>{m.key==="Enter"&&De()}}),e.jsx(z,{type:"button",size:"sm",disabled:!C.trim()||k,onClick:W(De),children:k?"Adding...":"Add"})]}),e.jsx(Ha,{competitors:s.competitors,onSelectCompetitor:m=>{u(m),document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})},activeFilter:oe})]}),e.jsx(hr,{projectName:s.project.name}),s.providerScores.length>1&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Model breakdown"}),e.jsxs("h2",{children:["Visibility by model ",e.jsx($e,{text:"Per-model citation rate today plus a sparkline of the recent run history. Same query set, different LLMs — gaps between providers point at content / source issues, not the metric."})]})]})}),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:"Model"}),e.jsx("th",{children:"Score"}),e.jsx("th",{children:"Trend"}),e.jsx("th",{children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(m=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(jt,{provider:m.provider}),m.model&&e.jsx("span",{className:"text-[11px] font-mono text-zinc-500",children:m.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:`font-semibold ${m.score>=70?"text-emerald-400":m.score>=40?"text-amber-400":"text-rose-400"}`,children:[m.score,"%"]})}),e.jsx("td",{children:e.jsx(tc,{trend:m.trend,currentScore:m.score})}),e.jsxs("td",{className:"text-zinc-500",children:[m.cited," of ",m.total]})]},`${m.provider}::${m.model??"unknown"}`))})]})})]}),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:"Run timeline"}),e.jsx("h2",{children:"Recent execution history"})]})}),e.jsx("div",{className:"run-list",children:s.recentRuns.map(m=>e.jsx(za,{run:m},m.id))})]})]}):t==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Qr,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:Ee,onRefresh:()=>{n()}}),e.jsx(Vr,{projectName:s.project.name}),e.jsx(Wr,{projectName:s.project.name})]}):t==="report"?e.jsx(Dr,{projectName:s.project.name}):t==="discovery"?e.jsx(vr,{projectName:se}):t==="activity"?e.jsx(Za,{projectName:s.project.name}):t==="backlinks"?e.jsx(ur,{projectName:s.project.name}):e.jsx(Jr,{projectName:s.project.name})]})}export{pc as ProjectPage};