PageSourceSearch

https://mlx.netsertive.com/assets/GenerativeSEO-DZuCnhGa.js

js netsertive.com collected 2026-09-24 09:30:34 UTC 102,558 bytes, 4 lines download raw bytes

1import{x as c,aT as he,z as e,bz as Hi,bA as Mi,bH as Xn}from"./vendor-DUAuXWev.js";import{A as ye,T as r,c as je,C as ze,ct as Ui,B as d,b6 as Se,b7 as Ae,b8 as Ie,M,aS as le,aU as de,bq as Fe,ai as q,d as an,g as Et,h as cn,j as Bt,_ as Gt,aQ as ln,aP as J,D as He,bb as ft,bX as qi,bl as Kt,bm as vt,bn as Xe,bf as jt,bo as Vt,bp as yt,bY as Zn,ch as ci,bZ as li,cg as Gi,cu as Ki,bv as oe,k as Ne,aa as di,cv as Ze,bk as Vi,L as zt,cw as Yi,e as lt,bz as dn,b3 as Ft,b4 as Ht,ad as dt,b5 as Mt,b as ei,P as Be,az as ht,aA as mt,aB as ut,aC as fe,aD as I,aE as pt,af as Ji,ax as ti,aj as Qi,ak as Xi,am as Zi,as as es}from"./vendor_ui-BBCpt_2H.js";import{a5 as hi,a4 as K,a3 as me,a7 as Oe,d as xt,a2 as hn,a8 as ts,a9 as gt}from"./index-BIF91r-S.js";import{p as ns}from"./jobs-ZeFhDQQV.js";import{P as is,a as ni}from"./PersonaIntelligencePanel-DjJdJGED.js";import{S as ue,a as mn,c as un}from"./siVocab-Blat70YK.js";import{a as ii,b as ss,s as rs}from"./aeoVisualSx-PC08Ec-C.js";import{d as pn}from"./locationDisplay-CxRZ4BA6.js";import{n as os}from"./dashboardGoals-qDXCPeiF.js";import{d as as}from"./downloadCsv-Dn4VJWn-.js";import{M as cs}from"./MarkdownRenderer-BuLU3Z8x.js";import{S as mi}from"./SearchIntelligencePageLayout-Bvuzemqu.js";import{T as ls}from"./ThemeContext-Dw3s77sW.js";const ds=()=>{const{selectedContext:s,selectedLocation:m}=hi(),g=(s==null?void 0:s.contextName)||"",[y,f]=c.useState(30),[_,h]=c.useState(!1),[v,b]=c.useState(!1),[S,w]=c.useState(null),[P,T]=c.useState([]),[X,pe]=c.useState([]),[ae,We]=c.useState([]),[F,Me]=c.useState(null),ne=he.useCallback(async()=>{if(g){h(!0);try{const C=Math.max(1,Math.min(3650,y)),U=`/api/generative-seo/${encodeURIComponent(g)}`,ie=m&&m!=="default"?`&location=${encodeURIComponent(m)}`:"",[Pe,G,Ke,Le]=await Promise.all([K.get(`${U}/citation-history?days=${C}${ie}`),K.get(`${U}/performance-score-history?days=${C}${ie}`),K.get(`${U}/position-history?days=${C}${ie}`),K.get(`${U}/patterns?days=${C}${ie}`)]);T(me(Pe)),pe(me(G)),We(me(Ke)),Me(Le&&typeof Le=="object"?Le:null)}catch(C){console.error("Error loading historical data:",C),T([]),pe([]),We([]),Me(null)}finally{h(!1)}}},[g,m,y]);c.useEffect(()=>{g&&ne()},[g,ne]);const be=he.useCallback(async()=>{var C,U,ie,Pe;if(g){w(null),b(!0);try{await K.post("/api/jobs/ai-overview",{contextName:g,location:m||"default",forceRefresh:!0});const G=await ns(g,m||"default",1e4);G.status==="completed"?(G.serpErrors&&G.serpErrors>0&&w(`Partially failed: ${G.serpErrors} prompts could not be checked. Reason: ${G.sampleSerpError}`),await ne()):G.status==="failed"&&w(G.error||"Run failed")}catch(G){const Ke=((U=(C=G==null?void 0:G.response)==null?void 0:C.data)==null?void 0:U.error)||((Pe=(ie=G==null?void 0:G.response)==null?void 0:ie.data)==null?void 0:Pe.message)||(G==null?void 0:G.message)||"Run failed";w(Ke)}finally{b(!1)}}},[g,m,ne]),ce=C=>new Date(C).toLocaleDateString("en-US",{month:"short",day:"numeric"}),et=C=>{switch(C){case"increasing":return e.jsx(Gt,{color:"success"});case"decreasing":return e.jsx(ln,{color:"error"});case"stable":return e.jsx(Ki,{color:"action"});default:return e.jsx(Fe,{color:"action"})}},Yt=C=>{switch(C){case"increasing":return"success";case"decreasing":return"error";case"stable":return"default";default:return"default"}};if(!g)return e.jsx(ye,{severity:"info",children:"Please select a client to view historical trends."});const bt=P.length>0||X.length>0||ae.length>0;if(!_&&!bt)return e.jsxs(ye,{severity:"info",sx:{mt:2},variant:"outlined",children:[e.jsx(r,{variant:"subtitle2",gutterBottom:!0,children:"No historical data yet"}),e.jsxs(r,{variant:"body2",paragraph:!0,sx:{mb:2},children:["Viewing this page does not collect data. Historical data is only stored when you run an ",e.jsx("strong",{children:"AI Overview check"}),". Run the check at least twice (on different days) to see trends. You can run it now below, or from the Prompts tab, or wait for the monthly refresh day in Settings."]}),S&&e.jsx(r,{color:"error",variant:"body2",sx:{mb:1},children:S}),e.jsx(je,{variant:"contained",size:"small",startIcon:v?e.jsx(ze,{size:16,color:"inherit"}):e.jsx(Ui,{}),onClick:be,disabled:v,children:v?"Running check…":"Run AI Overview check now"})]});if(_)return e.jsx(d,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"400px",children:e.jsx(ze,{})});const tt=F&&F.insights?F.insights:[];return(()=>{const C=[...P.map(ie=>ie.date),...X.map(ie=>ie.date),...ae.map(ie=>ie.date)];return!(C.length===0||[...new Set(C)].sort().length<2)})()?e.jsxs(d,{children:[e.jsxs(d,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:[e.jsx(r,{variant:"h5",fontWeight:"bold",children:"Historical Trends & Patterns"}),e.jsxs(Se,{size:"small",sx:{minWidth:150},children:[e.jsx(Ae,{children:"Time Period"}),e.jsxs(Ie,{value:y,label:"Time Period",onChange:C=>f(C.target.value),children:[e.jsx(M,{value:30,children:"Last 30 days"}),e.jsx(M,{value:60,children:"Last 60 days"}),e.jsx(M,{value:90,children:"Last 90 days"}),e.jsx(M,{value:180,children:"Last 6 months"}),e.jsx(M,{value:365,children:"Last year"})]})]})]}),F&&tt.length>0&&e.jsx(le,{sx:{mb:3},children:e.jsxs(de,{children:[e.jsxs(d,{display:"flex",alignItems:"center",gap:1,mb:2,children:[e.jsx(Fe,{color:"primary"}),e.jsx(r,{variant:"h6",children:"Trend Analysis"}),F.overallTrend!=="insufficient_data"&&F.overallTrend!=="error"&&e.jsx(q,{icon:et(F.overallTrend),label:F.overallTrend.charAt(0).toUpperCase()+F.overallTrend.slice(1),color:Yt(F.overallTrend),size:"small",sx:{ml:"auto"}})]}),e.jsxs(an,{children:[tt.map((C,U)=>e.jsxs(Et,{children:[e.jsx(cn,{children:e.jsx(Fe,{color:"primary",fontSize:"small"})}),e.jsx(Bt,{primary:C})]},U)),F.trendPercentage!==0&&F.overallTrend!=="insufficient_data"&&F.overallTrend!=="error"&&e.jsxs(Et,{children:[e.jsx(cn,{children:F.trendPercentage>0?e.jsx(Gt,{color:"success",fontSize:"small"}):e.jsx(ln,{color:"error",fontSize:"small"})}),e.jsx(Bt,{primary:`Overall trend: ${Math.abs(F.trendPercentage)}% ${F.trendPercentage>0?"increase":"decrease"} over this period`})]})]})]})}
1),e.jsxs(J,{container:!0,spacing:3,children:[e.jsx(J,{item:!0,xs:12,lg:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsx(r,{variant:"h6",gutterBottom:!0,children:"Citation History"}),e.jsx(He,{sx:{mb:2}}),P.length>0?e.jsx(d,{sx:{width:"100%",height:300},children:e.jsx(ft,{children:e.jsxs(qi,{data:P,children:[e.jsx(Kt,{strokeDasharray:"3 3"}),e.jsx(vt,{dataKey:"date",tickFormatter:ce,angle:-45,textAnchor:"end",height:80}),e.jsx(Xe,{yAxisId:"left"}),e.jsx(Xe,{yAxisId:"right",orientation:"right"}),e.jsx(jt,{labelFormatter:C=>ce(C),formatter:(C,U)=>U==="newCitations"||U==="lostCitations"?[C,U==="newCitations"?"New":"Lost"]:[C,U]}),e.jsx(Vt,{}),e.jsx(yt,{yAxisId:"right",dataKey:"newCitations",fill:"#2e7d32",name:"New Citations"}),e.jsx(yt,{yAxisId:"right",dataKey:"lostCitations",fill:"#c62828",name:"Lost Citations"}),e.jsx(Zn,{yAxisId:"left",type:"monotone",dataKey:"totalCitations",fill:"#1e76cf",fillOpacity:.3,stroke:"#1e76cf",name:"Total Citations"})]})})}):e.jsx(d,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:300,children:e.jsx(r,{color:"text.secondary",children:"No citation history data available"})})]})})}),e.jsx(J,{item:!0,xs:12,lg:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsx(r,{variant:"h6",gutterBottom:!0,children:"Performance Score Trend"}),e.jsx(He,{sx:{mb:2}}),X.length>0?e.jsx(d,{sx:{width:"100%",height:300},children:e.jsx(ft,{children:e.jsxs(ci,{data:X,children:[e.jsx(Kt,{strokeDasharray:"3 3"}),e.jsx(vt,{dataKey:"date",tickFormatter:ce,angle:-45,textAnchor:"end",height:80}),e.jsx(Xe,{domain:[0,100]}),e.jsx(jt,{labelFormatter:C=>ce(C),formatter:C=>[`${C}/100`,"Score"]}),e.jsx(Vt,{}),e.jsx(li,{type:"monotone",dataKey:"score",stroke:"#1e76cf",strokeWidth:3,dot:{r:4},name:"Performance Score"})]})})}):e.jsx(d,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:300,children:e.jsx(r,{color:"text.secondary",children:"No performance score history available"})})]})})}),e.jsx(J,{item:!0,xs:12,lg:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsx(r,{variant:"h6",gutterBottom:!0,children:"Average Position Trend"}),e.jsx(He,{sx:{mb:2}}),ae.length>0?e.jsx(d,{sx:{width:"100%",height:300},children:e.jsx(ft,{children:e.jsxs(Gi,{data:ae.filter(C=>C.avgPosition!==null),children:[e.jsx(Kt,{strokeDasharray:"3 3"}),e.jsx(vt,{dataKey:"date",tickFormatter:ce,angle:-45,textAnchor:"end",height:80}),e.jsx(Xe,{reversed:!0,domain:[1,"dataMax + 5"]}),e.jsx(jt,{labelFormatter:C=>ce(C),formatter:C=>[`#${C}`,"Position"]}),e.jsx(Vt,{}),e.jsx(Zn,{type:"monotone",dataKey:"avgPosition",stroke:"#1e76cf",fill:"#1e76cf",fillOpacity:.3,name:"Avg Position"})]})})}):e.jsx(d,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:300,children:e.jsx(r,{color:"text.secondary",children:"No position tracking data available"})})]})})}),e.jsx(J,{item:!0,xs:12,lg:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsx(r,{variant:"h6",gutterBottom:!0,children:"Significant Changes & Patterns"}),e.jsx(He,{sx:{mb:2}}),F&&F.anomalies.length>0?e.jsxs(d,{children:[e.jsx(r,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"Days with significant citation changes (>20%):"}),e.jsx(an,{dense:!0,children:F.anomalies.slice(0,10).map((C,U)=>e.jsxs(Et,{children:[e.jsx(cn,{children:C.type==="spike"?e.jsx(Gt,{color:"success",fontSize:"small"}):e.jsx(ln,{color:"error",fontSize:"small"})}),e.jsx(Bt,{primary:`${ce(C.date)}: ${C.type==="spike"?"+":"-"}${C.change} citations (${C.percentChange>0?"+":""}${C.percentChange}%)`})]},U))})]}):F&&F.seasonalTrend?e.jsxs(d,{children:[e.jsx(r,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"Weekly Pattern (Average Citations by Day):"}),e.jsx(an,{dense:!0,children:F.seasonalTrend.map((C,U)=>e.jsx(Et,{children:e.jsx(Bt,{primary:C.dayName,secondary:`${C.avgCitations.toFixed(1)} avg citations`})},U))})]}):e.jsx(d,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:200,children:e.jsx(r,{color:"text.secondary",children:"No patterns detected yet"})})]})})})]})]}):null};function ui(s){if(s==null)return null;if(typeof s=="number"&&Number.isFinite(s)){const y=s<1e11?s*1e3:s,f=new Date(y).getTime();return Number.isNaN(f)?null:f}let m=String(s).trim();if(!m)return null;if(/^\d{4}-\d{2}-\d{2}$/.test(m)){const y=Date.parse(`${m}T12:00:00`);return Number.isNaN(y)?null:y}const g=Date.parse(m);return Number.isNaN(g)?null:g}function hs(s){const m=ui(s);return m==null?"—":new Date(m).toLocaleDateString(void 0,{dateStyle:"medium"})}function ms({active:s,payload:m}){if(!s||!(m!=null&&m.length))return null;const g=m[0].payload;return e.jsxs(d,{sx:{bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1,px:1,py:.5,fontSize:12,boxShadow:1},children:[e.jsx(d,{sx:{fontWeight:600},children:g.dateLabel}),e.jsx(d,{sx:{color:"text.secondary"}
1,children:typeof g.value=="number"?g.value.toLocaleString():g.value})]})}const us=({points:s,color:m="#1976d2",height:g=52,yMode:y="count"})=>{const{data:f,yDomain:_}=c.useMemo(()=>{const h=s.map(P=>typeof P.value=="number"&&Number.isFinite(P.value)?P.value:0),v=Math.max(...h,0),b=Math.min(...h,0);let S;if(y==="score"||y==="percent")S=[0,100];else{const P=Math.max(v,1),T=Math.max((v-b)*.08,P*.04,1);S=[0,P+T]}return{data:s.map(P=>({x:ui(P.date)??0,value:typeof P.value=="number"&&Number.isFinite(P.value)?P.value:0,dateLabel:hs(P.date)})).filter(P=>P.x>0).sort((P,T)=>P.x-T.x),yDomain:S}},[s,y]);return f.length<2?null:e.jsx(d,{sx:{width:"100%",height:g,mt:"auto",pt:1,mx:-.5,display:"none"},children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(ci,{data:f,margin:{top:2,right:4,left:0,bottom:0},children:[e.jsx(vt,{dataKey:"x",type:"number",domain:["dataMin","dataMax"],hide:!0}),e.jsx(Xe,{domain:_,hide:!0}),e.jsx(jt,{content:e.jsx(ms,{}),cursor:{stroke:"#ccc",strokeWidth:1}}),e.jsx(li,{type:"linear",dataKey:"value",stroke:m,strokeWidth:2,dot:!1,isAnimationActive:!1})]})})})},fn=[{id:"google_aio",label:"Google AI Overviews"},{id:"perplexity",label:"Perplexity"},{id:"chatgpt",label:"ChatGPT"},{id:"bing_copilot",label:"Bing Copilot"},{id:"claude",label:"Claude"}];function ps(s){var m;return((m=fn.find(g=>g.id===s))==null?void 0:m.label)||s}const xs=({selected:s,onChange:m,available:g,showAverageHint:y=!0,dense:f=!1,refreshing:_=!1})=>{const h=g&&g.length>0?new Set(g):null,v=w=>{if(s.includes(w)){if(s.length===1)return;m(s.filter(P=>P!==w))}else m([...s,w])},b=()=>{const w=fn.map(P=>P.id).filter(P=>!h||h.has(P));m(w.length?w:["google_aio"])},S=s.map(ps);return e.jsxs(d,{sx:{mb:f?1:2},children:[e.jsxs(oe,{direction:"row",alignItems:"center",spacing:.5,sx:{mb:.5},children:[e.jsx(r,{variant:f?"body2":"subtitle2",color:"text.secondary",children:f?"Answer sources":"Filter metrics by answer engine"}),e.jsx(Ne,{title:"Pick one engine for that engine’s numbers, or several to average scores and counts across them. Averaged counts can be higher or lower than Google alone. Does not reload the whole page.",children:e.jsx(Fe,{fontSize:"small",color:"action",sx:{fontSize:16}})}),_?e.jsx(ze,{size:14,sx:{ml:.5}}):null]}),f?null:e.jsx(r,{variant:"caption",color:"text.secondary",sx:{display:"block",mb:1},children:"Click an engine to include or exclude it. Dimmed chips have no collected data yet."}),e.jsxs(oe,{direction:"row",flexWrap:"wrap",useFlexGap:!0,spacing:.75,sx:{alignItems:"center"},children:[fn.map(w=>{const P=!h||h.has(w.id),T=s.includes(w.id);return e.jsx(Ne,{title:P?T?"Included in the metrics below":`Click to include ${w.label} in the metrics below`:`No ${w.label} data collected yet for this client`,children:e.jsx("span",{children:e.jsx(q,{size:"small",label:w.label,color:T?"primary":"default",variant:T?"filled":"outlined",onClick:X=>{X.preventDefault(),X.stopPropagation(),v(w.id)},onMouseDown:X=>{X.preventDefault()},disabled:_,sx:{opacity:P||T?1:.55,fontWeight:T?600:400,cursor:_?"wait":"pointer"}})})},w.id)}),e.jsx(q,{size:"small",variant:"outlined",label:"All with data",disabled:_,onClick:w=>{w.preventDefault(),w.stopPropagation(),b()},onMouseDown:w=>w.preventDefault()})]}),y&&e.jsx(r,{variant:"caption",color:"text.secondary",sx:{display:"block",mt:.75,fontWeight:_?600:400},children:_?`Updating metrics for ${S.join(", ")}…`:s.length>1?`Averaging each engine’s score and counts (not a combined total). Engines: ${S.join(", ")}.`:`Showing ${S[0]} only.`})]})};function si(s,m=700){const g=typeof s=="number"&&Number.isFinite(s)?s:null,[y,f]=c.useState(0);return c.useEffect(()=>{if(g==null){f(0);return}let _=0;const h=performance.now(),v=0,b=S=>{const w=Math.min(1,(S-h)/m),P=1-(1-w)**3;f(v+(g-v)*P),w<1&&(_=requestAnimationFrame(b))};return _=requestAnimationFrame(b),()=>cancelAnimationFrame(_)},[g,m]),g==null?0:y}const gs=({loading:s,score:m,level:g,color:y,coveragePct:f,clientCitations:_,totalCitations:h,answersFound:v,brandDomain:b,sparkline:S,subtitle:w,metricSources:P,availableMetricSources:T,onMetricSourcesChange:X,metricsRefreshing:pe=!1})=>{const ae=di(),We=rs(y),F=si(m??null),Me=si(f??null),ne=((P==null?void 0:P.length)??0)>1,be=We==="default"?ae.palette.primary.main:ae.palette[We].main;return s?e.jsxs(d,{sx:ii,children:[e.jsx(Ze,{variant:"text",width:180,height:28}),e.jsx(Ze,{variant:"text",width:120,height:72,sx:{mt:1}}),e.jsx(Ze,{variant:"rounded",height:40,sx:{mt:2,maxWidth:520}}),e.jsx(Ze,{variant:"rounded",height:56,sx:{mt:2}})]}):e.jsxs(d,{sx:ii,children:[e.jsx(d,{sx:{position:"absolute",right:-40,top:-40,width:180,height:180,borderRadius:"50%",bgcolor:be,opacity:.08,pointerEvents:"none"}}),P&&X?e.jsx(d,{sx:{mb:2,position:"relative",zIndex:1},children:e.jsx(xs,{selected:P,onChange:X,available:T,refreshing:pe,dense:!0})}):null,e.jsxs(oe,{direction:{xs:"column",md:"row"},spacing:{xs:2.5,md:4},alignItems:{xs:"flex-start",md:"center"},justifyContent:"space-between",sx:{opacity:pe?.55:1,transition:"opacity 0.2s ease"},children:[e.jsxs(d,{sx:{minWidth:0,flex:1},children:[e.jsx(r,{variant:"overline",sx:{letterSpacing:1.2,color:"text.secondary",fontWeight:600},children:"Answer visibility"}),e.jsxs(oe,{direction:"row",alignItems:"baseline",spacing:1.5,sx:{mt:.5},children:[e.jsx(r,{variant:"h2",sx:{fontWeight:800,fontVariantNumeric:"tabular-nums",lineHeight:1,color:be},children:m!=null?Math.round(F):"—"}),g?e.jsx(q,{size:"small",label:g,sx:{fontWeight:700,bgcolor:`${be}18`,color:be}}):null]}),w?e.jsx(r,{variant:"body2",color:"text.secondary",sx:{mt:1,maxWidth:420},children:w}):null,S&&S.length>=2?e.jsx(d,{sx:{mt:1.5,maxWidth:280},children:e.jsx(us,{points:S,yMode:"score",color:be})}):null]}),e.jsxs(oe,{direction:"row",spacing:{xs:2,sm:2.5,md:3},flexWrap:"wrap",useFlexGap:!0,sx:ss,children:[e.jsx(Ut,{label:ne?ue.avgAnswered:ue.answeredCount,value:v!=null?String(v):"—",hint:ne?"per engine":void 0}),e.jsx(Ut,{label:ne?`Avg ${ue.totalCitations.toLowerCase()}`:ue.totalCitations,value:h!=null?String(h):"—",hint:ne?"per engine":void 0}),e.jsx(Ut,{label:ne?`Avg ${ue.yourCitations.toLowerCase()}`:ue.yourCitations,value:_!=null?String(_):"—",hint:b||(ne?"per engine":void 0),emphasize:!0}),e.jsx(Ut,{label:ue.citationCoverage,value:f!=null?`${Math.round(Me)}%`:"—",hint:ne?"avg % of prompts that cite you":"of prompts that cite you"})]})]})]})};function Ut({label:s,value:m,hint:g,emphasize:y}){return e.jsxs(d,{sx:{minWidth:96},children:[e.jsx(r,{variant:"caption",color:"text.secondary",sx:{textTransform:"uppercase",letterSpacing:.6,display:"block"},children:s}),e.jsx(r,{variant:"h5",sx:{fontWeight:700,fontVariantNumeric:"tabular-nums",color:y?"success.dark":"text.primary",mt:.25},children:m}
1),g?e.jsx(r,{variant:"caption",color:"text.secondary",sx:{display:"block",mt:.25},children:g}):null]})}const ri=["google_aio","chatgpt","perplexity","bing_copilot","claude"];function fs(s){const m=Object.entries(s||{});return m.length===0?[]:[...m].sort(([y],[f])=>{const _=ri.indexOf(y),h=ri.indexOf(f);return(_===-1?99:_)-(h===-1?99:h)}).map(([y,f])=>{const _=f.prompts_with_aio??f.total_ai_overviews??0,h=f.prompts_cited??0,v=f.client_citations??0;return{id:y,name:f.label||y,answered:_,cited:h,yourCitations:v,coverage:Math.round(f.prompt_coverage??0),citeRate:_>0?h/_:0}})}function vs(s){const m=s.filter(v=>v.answered>0||v.cited>0||v.yourCitations>0);if(m.length===0)return[];const y=[...m].sort((v,b)=>b.yourCitations-v.yourCitations||b.cited-v.cited)[0],f=[...m].filter(v=>v.answered>=5&&v.citeRate<.45).sort((v,b)=>b.answered-v.answered||v.citeRate-b.citeRate),_=[];y&&y.yourCitations>0&&_.push({engine:y.name,verdict:"Lead here",detail:`Most of your citations are on ${y.name} (${y.yourCitations}). Prefer content and prompts that defend this presence.`,tone:"win"});for(const v of f.slice(0,2))v.id===(y==null?void 0:y.id)&&_.length>0||_.push({engine:v.name,verdict:"Grow citations",detail:`${v.name} answers ${v.answered} of your prompts but only cites you on ${v.cited}. Strong place to invest if buyers use this engine.`,tone:"opportunity"});const h=m.filter(v=>v.answered>0&&v.answered<5&&v.yourCitations===0);for(const v of h.slice(0,1))_.some(b=>b.engine===v.name)||_.push({engine:v.name,verdict:"Light coverage",detail:`Few answers collected on ${v.name} yet. Collect more runs before deciding to prioritize it.`,tone:"thin"});return _.slice(0,3)}const js={win:"success.main",opportunity:"warning.main",thin:"text.secondary"},ys=({sourceMetrics:s,loading:m=!1})=>{const g=c.useMemo(()=>fs(s),[s]),y=c.useMemo(()=>g.map(h=>({name:h.name,answered:h.answered,cited:h.cited,yourCitations:h.yourCitations})),[g]),f=c.useMemo(()=>vs(g),[g]),_=g.some(h=>h.answered>0||h.cited>0||h.yourCitations>0);return m?e.jsxs(d,{sx:{mb:3},children:[e.jsx(Ze,{variant:"text",width:280,height:32}),e.jsx(Ze,{variant:"rectangular",height:220,sx:{mt:1,borderRadius:1}})]}):_?e.jsxs(d,{sx:{mb:3},children:[e.jsx(r,{variant:"h6",fontWeight:600,sx:{mb:.5},children:"Which engines to prioritize"}),e.jsx(r,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"Based on where your brand is answered and cited across tracked prompts — use this to choose where sales and content should focus."}),f.length>0&&e.jsx(oe,{spacing:1.25,sx:{mb:2.5},children:f.map(h=>e.jsxs(d,{sx:{pl:1.5,borderLeft:"3px solid",borderColor:js[h.tone],py:.5},children:[e.jsxs(r,{variant:"subtitle2",fontWeight:600,children:[h.verdict,": ",h.engine]}),e.jsx(r,{variant:"body2",color:"text.secondary",children:h.detail})]},`${h.verdict}-${h.engine}`))}),e.jsx(d,{sx:{height:260,px:{xs:0,sm:1},py:1,borderRadius:1,bgcolor:"action.hover"},children:e.jsx(ft,{width:"100%",height:"100%",children:e.jsxs(Vi,{data:y,margin:{top:8,right:16,left:0,bottom:4},children:[e.jsx(Kt,{strokeDasharray:"3 3",vertical:!1}),e.jsx(vt,{dataKey:"name",tickLine:!1,interval:0,tick:{fontSize:12}}),e.jsx(Xe,{allowDecimals:!1,tickLine:!1,axisLine:!1,width:36}),e.jsx(jt,{formatter:(h,v)=>{const b={answered:ue.answered,cited:ue.cited,yourCitations:ue.yourCitations};return[h,b[v]||v]}}),e.jsx(Vt,{formatter:h=>({answered:ue.answered,cited:ue.cited,yourCitations:ue.yourCitations})[h]||h}),e.jsx(yt,{dataKey:"answered",fill:"#90caf9",radius:[4,4,0,0]}),e.jsx(yt,{dataKey:"cited",fill:"#1976d2",radius:[4,4,0,0]}),e.jsx(yt,{dataKey:"yourCitations",fill:"#0d47a1",radius:[4,4,0,0]})]})})})]}):e.jsxs(d,{sx:{mb:3},children:[e.jsx(r,{variant:"h6",fontWeight:600,sx:{mb:.5},children:"Which engines to prioritize"}),e.jsx(ye,{severity:"info",children:"Collect answer-engine runs (Google AI Overviews, ChatGPT, Perplexity, and others) to see where you already win and where to invest next."})]})},bs=s=>{if(s==null)return"";const m=String(s);return m.includes(",")||m.includes('"')||m.includes(`
2`)?`"${m.replace(/"/g,'""')}"`:m},re=s=>s.map(bs).join(","),ws=s=>{const{contextName:m,domain:g,dateRange:y,metrics:f,prompts:_}=s,h=[];h.push("Answer Engine Optimization Report"),h.push(`Context: ${m}`),h.push(`Domain: ${g}`),y&&h.push(`Date Range: ${y.start} to ${y.end}
2`),h.push(`Generated: ${new Date().toLocaleString()}`),h.push(""),h.push("METRICS SUMMARY"),h.push(re(["Metric","Value"])),h.push(re(["Total Prompts",f.totalPrompts])),h.push(re(["Prompts with AI Overview",f.totalAiOverviews])),h.push(re(["Prompts Cited",f.promptsCited])),h.push(re(["Total Citations",f.contextCitations])),h.push(re(["Coverage Percentage",`${f.coveragePercentage.toFixed(1)}%`])),h.push(re(["Average Position",f.avgPosition>0?`#${f.avgPosition.toFixed(1)}`:"N/A"])),h.push(""),f.competitor_metrics&&Object.keys(f.competitor_metrics).length>0&&(h.push("COMPETITOR METRICS"),h.push(re(["Competitor","Total Citations","Cited Prompts","Coverage %","Avg Position"])),Object.entries(f.competitor_metrics).forEach(([S,w])=>{h.push(re([S,w.total_citations||0,w.cited_prompts||0,`${(w.coverage_percentage||0).toFixed(1)}%`,w.avg_position&&w.avg_position>0?`#${w.avg_position.toFixed(1)}`:"N/A"]))}),h.push("")),h.push("PROMPTS DATA"),h.push(re(["Prompt","Intent","Stage","Topic","Has AI Overview","Cited","Citation Count","Avg Citation Position","Organic Position","Competitor Positions"])),_.forEach(S=>{var X;const w=((X=S.citations)==null?void 0:X.length)||0,P=S.citations&&S.citations.length>0?(S.citations.reduce((pe,ae)=>pe+(ae.position||0),0)/S.citations.length).toFixed(1):"N/A",T=S.competitor_organic_positions?Object.entries(S.competitor_organic_positions).map(([pe,ae])=>`${pe}: #${ae}`).join("; "):"N/A";h.push(re([S.text,S.intent,S.stage,S.topic||"general",S.hasAio?"Yes":"No",S.cited?"Yes":"No",w,P,S.context_organic_position?`#${S.context_organic_position}`:"N/A",T]))}),h.push(""),h.push("CITATIONS DETAIL"),h.push(re(["Prompt","Citation Position","Domain","URL","Title"])),_.forEach(S=>{S.citations&&S.citations.length>0&&S.citations.forEach(w=>{h.push(re([S.text.substring(0,100),w.position||"N/A",w.domain||"N/A",w.url||"N/A",w.title||"N/A"]))})}),h.push("");const v=_.filter(S=>S.context_organic_position);v.length>0&&(h.push("ORGANIC RANKINGS"),h.push(re(["Prompt","Your Position","Competitor Positions"])),v.forEach(S=>{const w=S.competitor_organic_positions?Object.entries(S.competitor_organic_positions).map(([P,T])=>`${P}: #${T}`).join("; "):"N/A";h.push(re([S.text,S.context_organic_position?`#${S.context_organic_position}`:"N/A",w]))}));const b=h.join(`
3`);as(b,`AEO_Report_${m}_${new Date().toISOString().split("T")[0]}.csv`)};var oi={};function xn(s){const m=(s.title||"").trim(),g=(s.description||"").trim(),y=`${m}
4${g}`;let f=2166136261;for(let _=0;_<y.length;_+=1)f^=y.charCodeAt(_),f=Math.imul(f,16777619);return`fp:${(f>>>0).toString(36)}`}function ai(s,m,g,y){var h;const _=((h=(y||"").replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0])==null?void 0:h.trim())||"default";return`aeo-overview-rec-dismissed:${encodeURIComponent(s)}:${encodeURIComponent(m)}:${encodeURIComponent(g)}:${encodeURIComponent(_)}`}function ve(){const s=ts();if(!(s!=null&&s.email))return!1;const m=s.email.toLowerCase();if(["[email protected]","[email protected]"].includes(m))return!1;const y=typeof process<"u"?oi.REACT_APP_ADMIN_EMAILS:void 0,f=typeof window<"u"?window.REACT_APP_ADMIN_EMAILS:void 0,h=(y||f||"").split(",").map(w=>w.trim().toLowerCase()).filter(Boolean),v=typeof process<"u"?oi.REACT_APP_ADMIN_DOMAIN:void 0,b=typeof window<"u"?window.REACT_APP_ADMIN_DOMAIN:void 0,S=(v||b||"netsertive.com").toLowerCase();return h.includes(m)||m.endsWith(`@${S}`)}const Cs=new Set(["a","an","the","of","for","to","in","on","and","or","with","near","best","top","cheap","buy","price","pricing","cost","vs","review","reviews","how","what","why","when","where","guide","tips","service","services","company","companies"]),_s=s=>{const g=(s||"").toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(y=>y&&!Cs.has(y));return g.length===0?"general":g.slice(0,4).join(" ")},Ss=(s,m)=>{const g=(s||"").toString().trim().toLowerCase();return g&&g!=="general"&&g!=="misc"?g:_s(m)},As=s=>{if(s==null)return null;if(typeof s=="boolean")return s;if(typeof s=="number")return s===1;const m=String(s).trim().toLowerCase();return["true","t","1","yes","y"].includes(m)?!0:["false","f","0","no","n"].includes(m)?!1:null},qt=s=>{const m=String(s||"").trim();if(!m)return"";try{const g=m.indexOf("#"),y=g!==-1?m.slice(0,g):m,f=/^https?:\/\//i.test(y)?y:`https://${y}`,_=new URL(f),h=_.hostname.replace(/^www\./i,"").toLowerCase(),v=(_.pathname||"/").replace(/\/$/,"")||"/",b=_.search||"";return`${h}${v}${b}`}catch{return m.split("#")[0].toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,"")}},Ge=({title:s,children:m})=>e.jsxs(d,{sx:{mb:3},children:[e.jsx(r,{variant:"h6",sx:{mb:1},children:s}),m]}),gn=14*24*60*60*1e3,Is=()=>{var Kn,Vn,Yn,Jn,Qn;di();const[s,m]=c.useState(null),[g,y]=c.useState(["google_aio"]),[f,_]=c.useState(!1),[h,v]=c.useState(["google_aio"]),[b,S]=c.useState([]),[w,P]=c.useState([]),[T,X]=c.useState(null),[pe,ae]=c.useState(!1),[We,F]=c.useState(!1),[Me,ne]=c.useState(null),[,be]=c.useState(null),[ce,et]=c.useState([]),[Yt,bt]=c.useState(!1),[tt,nt]=c.useState(()=>new Set),[C,U]=c.useState(!0),[ie,Pe]=c.useState(null),G=he.useRef(null);he.useEffect(()=>{G.current=s},[s]);const[Ke,Le]=c.useState([]),[vn,wt]=c.useState([]),{selectedContext:L,selectedLocation:it,setSelectedLocation:pi,loading:Jt,locationRestricted:Qt}
4=hi(),H=Hi(),te=Mi(),jn=c.useCallback(t=>{if(!t)return;const n=new URLSearchParams(H.search);n.set("tab","prompts"),n.set("promptId",t),te(`${H.pathname}?${n.toString()}`)},[te,H.pathname,H.search]),Ve=c.useMemo(()=>{const t=new URLSearchParams(H.search).get("promptId");return t&&t.trim()?t.trim():null},[H.search]),yn=c.useCallback(t=>{const n=new URLSearchParams(H.search);n.set("tab","prompts"),t?n.set("promptId",t):n.delete("promptId"),te(`${H.pathname}?${n.toString()}`,{replace:!0})},[te,H.pathname,H.search]),V=(L==null?void 0:L.primaryDomain)||(L==null?void 0:L.domains[0])||"",u=(L==null?void 0:L.contextName)||"",k=c.useMemo(()=>{const t=(L==null?void 0:L.locations)??[];return!it||it==="default"||!t.length?"default":t.some(n=>n.location===it)?it:"default"},[it,L==null?void 0:L.locations]),[$,xi]=c.useState("main"),[Xt,gi]=c.useState(!0),[Zt,bn]=c.useState([{value:"main",label:"You"}]),De=Zt.length>1,fi=c.useCallback(async()=>{if(u){ae(!0);try{await K.post(`/api/generative-seo/${encodeURIComponent(u)}/sentiment/score`,{location:k||"default",forceRefresh:!1,limit:40});const t=await K.get(`/api/generative-seo/${encodeURIComponent(u)}/sentiment?location=${encodeURIComponent(k)}`),n=t!=null&&t.overall?t:(t==null?void 0:t.data)||t;X({overall:(n==null?void 0:n.overall)||{positive:0,neutral:0,negative:0},details:(n==null?void 0:n.details)||[],by_topic:(n==null?void 0:n.by_topic)||[],by_persona:(n==null?void 0:n.by_persona)||[]})}catch(t){console.error("Sentiment score failed",t)}finally{ae(!1)}}},[u,k]),vi=c.useCallback(async()=>{if(u){F(!0),ne(null);try{const t=await K.post(`/api/generative-seo/${encodeURIComponent(u)}/citation-source-audit`,{location:k||"default",limit:30});ne(`Audited ${(t==null?void 0:t.audited)??0} influential sources; ${(t==null?void 0:t.withBrandMention)??0} mention your brand.`)}catch(t){ne(t instanceof Error?t.message:"Citation audit failed")}finally{F(!1)}}},[u,k]);c.useEffect(()=>{u&&(m(null),S([]),P([]),X(null),be(null),et([]),bn([{value:"main",label:"You"}]),Le([]),wt([]),ne(null))},[u,k]),c.useEffect(()=>{if(!u){Le([]),wt([]);return}let t=!1;const n=k!=="default"?`&location=${encodeURIComponent(k)}`:"",i=`/api/generative-seo/${encodeURIComponent(u)}`;return(async()=>{try{const[o,a]=await Promise.all([K.get(`${i}/citation-history?days=120${n}`),K.get(`${i}/performance-score-history?days=120${n}`)]);if(t)return;wt(me(o)),Le(me(a))}catch{t||(wt([]),Le([]))}})(),()=>{t=!0}},[u,k]);const Te=w.length>=2,E=c.useMemo(()=>{let t=6;const n={overview:0,insights:1,prompts:2,serp:3,actions:4,recommendationsHistory:5};return De?n.competitors=t++:n.competitors=-1,Te?n.history=t++:n.history=-1,n},[De,Te]),ji=c.useMemo(()=>{const t=[...Ke].sort((i,o)=>i.date.localeCompare(o.date)),n=[...vn].sort((i,o)=>i.date.localeCompare(o.date));return{performance:t.map(i=>({date:i.date,value:i.score})),aioImpressions:t.map(i=>{var o;return{date:i.date,value:((o=i.metrics)==null?void 0:o.promptsWithAio)??0}}),coverage:t.map(i=>{var o;return{date:i.date,value:((o=i.metrics)==null?void 0:o.coverage)??0}}),totalCitations:n.map(i=>({date:i.date,value:i.totalCitations??0})),yourCitations:n.map(i=>({date:i.date,value:typeof i.clientCitations=="number"?i.clientCitations:0}))}},[Ke,vn]),Ct=c.useCallback(t=>{for(const[n,i]of Object.entries(E))if(i===t)return n;return null},[E]),en=c.useCallback(t=>{const n=String(t||"").trim().toLowerCase();if(!n)return null;for(const[i,o]of Object.entries(E))if(i.toLowerCase()===n&&o>=0)return o;return null},[E]),[Z,_t]=c.useState(()=>{const n=new URLSearchParams(H.search).get("tab");if(n){const i=en(n);if(i!==null)return i;const o=parseInt(n,10);let a=5;if(De&&a++,Te&&a++,!isNaN(o)&&o>=0&&o<=a)return o}return 0}),[St,wn]=c.useState("all"),[At,Cn]=c.useState("all"),[It,_n]=c.useState("all"),[Pt,yi]=c.useState("all"),[kt,Sn]=c.useState("all"),[$t,An]=c.useState("all"),[tn,In]=c.useState(""),[nn,bi]=c.useState(!1),[wi,Ci]=c.useState(()=>new Set),_i=Zt.length>1&&[E.overview,E.insights,E.prompts,E.actions,E.competitors].includes(Z),Pn=c.useCallback(()=>{te("/personas")},[te]),kn=c.useCallback(()=>{te("/personas?create=1")},[te]);c.useCallback((t,n)=>{_t(n);const i=new URLSearchParams(H.search),o=Ct(n);n===0||!o?i.delete("tab"):i.set("tab",o),n!==E.prompts&&i.delete("promptId");const a=i.toString();te(`${H.pathname}${a?`?${a}`:""}`,{replace:!0})},[H.search,H.pathname,te,Ct,E.prompts]);const Si=c.useCallback(t=>{Ci(n=>{const i=new Set(n);return i.has(t)?i.delete(t):i.add(t),i})},[]),Ai=c.useMemo(()=>Array.from(new Set(b.map(n=>
4String(n.intent||"").trim()).filter(Boolean))).sort((n,i)=>n.localeCompare(i)),[b]),Ii=c.useMemo(()=>Array.from(new Set(b.map(n=>String(n.stage||"").trim()).filter(Boolean))).sort((n,i)=>n.localeCompare(i)),[b]),Rt=c.useMemo(()=>{const t=tn.trim().toLowerCase();return b.filter(n=>!(t&&!String(n.text||"").toLowerCase().includes(t)||St!=="all"&&String(n.intent||"")!==St||At!=="all"&&String(n.stage||"")!==At||It==="branded"&&n.branded!==!0||It==="unbranded"&&n.branded===!0||kt==="with"&&!n.hasAio||kt==="without"&&n.hasAio||$t==="cited"&&!n.cited||$t==="not_cited"&&n.cited))},[b,tn,St,At,It,kt,$t]),$n=c.useMemo(()=>[...Rt].sort((t,n)=>{const i=t.cited?1:0,o=n.cited?1:0;if(i!==o)return o-i;const a=t.hasAio?1:0,p=n.hasAio?1:0;return a!==p?p-a:String(t.text||"").localeCompare(String(n.text||""))}),[Rt]),Ot=c.useMemo(()=>{const t=new Map;for(const n of $n){const i=String(n.text||"").trim().toLowerCase();if(!i)continue;const o=t.get(i);if(!o){t.set(i,{prompt:n,count:1});continue}o.count+=1;const a=(o.prompt.cited?4:0)+(o.prompt.hasAio?2:0)+(o.prompt.branded===!0?1:0);(n.cited?4:0)+(n.hasAio?2:0)+(n.branded===!0?1:0)>a&&(o.prompt=n)}return Array.from(t.values())},[$n]),Rn=c.useMemo(()=>{const t=new Map;for(const n of b){const i=[...n.citations||[],...n.citation_contexts||[]],o=new Set;for(const a of i){const p=a.url;if(!p)continue;const A=qt(p);if(!A||o.has(A))continue;o.add(A);const l=t.get(A)||[];l.some(N=>N.promptId===n.promptId)||(l.push({promptId:n.promptId,text:n.text||"Tracked prompt"}),t.set(A,l))}}for(const n of t.values())n.sort((i,o)=>i.text.localeCompare(o.text));return t},[b]);c.useEffect(()=>{if(Z!==E.prompts||!Ve||!Ot.some(({prompt:o})=>String(o.promptId)===String(Ve)))return;const n=`aeo-prompt-accordion-${Ve}`,i=window.setTimeout(()=>{var o;(o=document.getElementById(n))==null||o.scrollIntoView({behavior:"smooth",block:"nearest"})},150);return()=>window.clearTimeout(i)},[Z,E.prompts,Ve,Ot]);const Ye=c.useMemo(()=>{const t=new Map;for(const n of b){const i=Array.isArray(n.citations)?n.citations:[];for(const o of i){let a=String(o.domain||"").trim().toLowerCase();if(!a&&o.url)try{a=new URL(o.url).hostname.toLowerCase()}catch{a=""}if(a=a.replace(/^www\./,""),!a)continue;const p=t.get(a)||{domain:a,citationCount:0,promptIds:new Set,urlAggregates:new Map};p.citationCount+=1,p.promptIds.add(n.promptId);const A=String(o.url||"").trim();if(A){const l=qt(A);if(l){const N=A.split("#")[0],W=p.urlAggregates.get(l);W?W.count+=1:p.urlAggregates.set(l,{displayHref:N,count:1})}}t.set(a,p)}}return Array.from(t.values()).map(n=>({domain:n.domain,promptCount:n.promptIds.size,citationCount:n.citationCount,citedUrls:Array.from(n.urlAggregates.values()).sort((i,o)=>o.count-i.count||i.displayHref.localeCompare(o.displayHref))})).sort((n,i)=>i.citationCount-n.citationCount||i.promptCount-n.promptCount).slice(0,25)},[b]),Pi=c.useMemo(()=>nn?Ye:Ye.slice(0,10),[nn,Ye]),st=c.useMemo(()=>{const t=l=>String(l||"").trim().toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,""),n=b.filter(l=>Pt==="branded"?l.branded===!0:Pt==="unbranded"?l.branded!==!0:!0),o=n.filter(l=>!!l.hasAio).length||n.length||1,a=t($==="main"?V:$),p=n.reduce((l,N)=>{const D=(Array.isArray(N.citations)?N.citations:[]).filter(Q=>{const xe=t(Q.domain||""),Re=t(Q.url||"");return!!a&&(xe.includes(a)||Re.includes(a))});return D.length>0&&(l.citedPrompts+=1),l.totalCitations+=D.length,l},{totalCitations:0,citedPrompts:0}),A=Object.entries((s==null?void 0:s.competitor_metrics)||{}).reduce((l,[N])=>{const W=t(N),D=n.reduce((Q,xe)=>{const we=(Array.isArray(xe.citations)?xe.citations:[]).filter(Ce=>{const ge=t(Ce.domain||""),_e=t(Ce.url||"");return ge.includes(W)||_e.includes(W)});return we.length>0&&(Q.cited_prompts+=1),Q.total_citations+=we.length,Q},{total_citations:0,cited_prompts:0});return l[N]={...D,coverage_percentage:D.cited_prompts/o*100},l},{});return{promptsCount:n.length,selectedBrandMetrics:{totalCitations:p.totalCitations,citedPrompts:p.citedPrompts,coveragePercentage:p.citedPrompts/o*100},competitorMetrics:A}},[b,Pt,$,V,s==null?void 0:s.competitor_metrics]);c.useEffect(()=>{const n=new URLSearchParams(H.search).get("tab");if(n==="personas"){te("/personas",{replace:!0});return}if(n==="prompts"){te("/prompts",{replace:!0});return}let i=5;De&&i++,Te&&i++;let o=0;if(n){const a=en(n);if(a!==null)o=a;else{const p=parseInt(n,10);!isNaN(p)&&p>=0&&p<=i&&(o=p)}}_t(a=>a!==o?o:a)},[H.search,De,Te,en,te]),c.useEffect(()=>{let t=5;if(De&&t++,Te&&t++,Z>t){_t(t);const n=new URLSearchParams(H.search),i=Ct(t);i?n.set("tab",i):n.set("tab",t.toString()),te(`${H.pathname}?${n.toString()}`,{replace:!0})}},[Z,De,Te,H.pathname,H.search,te,Ct]);const[ki,sn]=c.useState(!1),[Je,$i]=c.useState(""),[B,On]=c.useState(null),[Ri,Nn]=c.useState(!1),Oi=()=>$==="main"?V:$,Wn=(t,n,i)=>
4`aeo-recommendations:${t}:${n}:${i}`;c.useEffect(()=>{if(!u){nt(new Set);return}const t=ai(u,$,k,V||"");try{const n=localStorage.getItem(t),i=n?JSON.parse(n):[],o=Array.isArray(i)?i.filter(a=>typeof a=="string"):[];nt(new Set(o))}catch{nt(new Set)}},[u,$,k,V]);const Ni=c.useCallback(t=>{if(!u)return;const n=xn(t);nt(i=>{if(i.has(n))return i;const o=new Set(i);o.add(n);const a=ai(u,$,k,V||"");try{localStorage.setItem(a,JSON.stringify([...o]))}catch{}return o})},[u,$,k,V]),Ln=c.useMemo(()=>ce.filter(t=>!tt.has(xn(t))),[ce,tt]),[Ue,Nt]=c.useState([]),[Wt,Dn]=c.useState(!1),[Wi,Tn]=c.useState({}),[Li,En]=c.useState({}),[ke,Di]=c.useState(!1),[Lt,Bn]=c.useState("all"),zn=c.useMemo(()=>{const t=b.filter(a=>a.hasAio&&!a.cited),n={transactional:0,commercial_investigation:1,nav:2,info:3},i={bottom:0,mid:1,top:2},o=a=>a.priority??.5;return t.sort((a,p)=>{if(o(p)!==o(a))return o(p)-o(a);const A=n[a.intent]??4,l=n[p.intent]??4;return A!==l?A-l:(i[a.stage]??3)-(i[p.stage]??3)}),t.map(a=>{var A;const p=((A=a.citations)==null?void 0:A.length)??0;return{...a,citationCount:p}})},[b]),rn=c.useMemo(()=>Lt==="actioned"?Ue.filter(t=>t.actioned):Lt==="not_actioned"?Ue.filter(t=>!t.actioned):Ue,[Ue,Lt]),Fn=Wt||Ue.length>0,$e=c.useCallback(async()=>{var t;if(u){Dn(!0);try{const n=k,i=(t=(V||"").replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0])==null?void 0:t.trim();let o=`/api/generative-seo/${encodeURIComponent(u)}/recommendation-history?limit=100&location=${encodeURIComponent(n)}`;i&&(o+=`&domainForContext=${encodeURIComponent(i)}`);const a=await K.get(o);Nt(me(a,{keys:["items","data","results","records"]}));const p=a.showInPortalColumnOnHistory;Di(p===!0)}catch(n){console.error("Failed to load recommendation history:",n),Nt([])}finally{Dn(!1)}}},[u,k,V]),Hn=c.useCallback(()=>{if(u){Oe.clearClient(u);try{const t=`aeo-recommendations:${u}:`,n=[];for(let i=0;i<localStorage.length;i++){const o=localStorage.key(i);o&&o.startsWith(t)&&n.push(o)}n.forEach(i=>localStorage.removeItem(i))}catch{}window.dispatchEvent(new CustomEvent("aeo-recommendations-refreshed",{detail:{contextName:u}}));try{localStorage.setItem("aeo-recommendations-refresh-requested",JSON.stringify({contextName:u,at:Date.now()}))}catch{}}},[u]),Ti=c.useCallback(async(t,n)=>{if(u){Tn(i=>({...i,[t]:!0}));try{const i=await K.patch(`/api/generative-seo/${encodeURIComponent(u)}/recommendation-history/${t}`,{actioned:n,location:k}),o=(i==null?void 0:i.actioned)??n,a=(i==null?void 0:i.actionedAt)!=null?i.actionedAt:o?new Date().toISOString():null;Nt(p=>p.map(A=>A.id===t?{...A,actioned:o,actionedAt:a}:A))}catch(i){console.error("Failed to update recommendation actioned:",i)}finally{Tn(i=>({...i,[t]:!1}))}}},[u,k]),Ei=c.useCallback(async(t,n)=>{if(!(!u||!ve())){En(i=>({...i,[t]:!0})),Nt(i=>i.map(o=>o.id===t?{...o,shownInPortal:n}:o));try{await K.patch(`/api/generative-seo/${encodeURIComponent(u)}/recommendation-history/${t}`,{shownInPortal:n,location:k}),Hn()}catch(i){console.error("Failed to update recommendation portal visibility:",i),await $e()}finally{En(i=>({...i,[t]:!1}))}}},[u,k,$e,Hn]);c.useEffect(()=>{u&&$e()},[u,k,V,$e]),c.useEffect(()=>{Z===E.recommendationsHistory&&u&&$e()},[Z,E.recommendationsHistory,u,$e]),c.useEffect(()=>{if(Wt||Z!==E.recommendationsHistory||Fn)return;_t(E.overview);const t=new URLSearchParams(H.search);t.delete("tab"),te(`${H.pathname}${t.toString()?`?${t.toString()}`:""}`,{replace:!0})},[Wt,Z,E.recommendationsHistory,E.overview,Fn,H.pathname,H.search,te]),c.useEffect(()=>{Bn("all")},[u,k]);const Mn=c.useCallback(async()=>{if(u){Nn(!0);try{const t=await K.get(`/api/generative-seo/${encodeURIComponent(u)}/goals`);On({targetCitationSharePct:t.targetCitationSharePct!=null?t.targetCitationSharePct:null,targetCitedCount:t.targetCitedCount!=null?t.targetCitedCount:null,targetPerformanceScore:t.targetPerformanceScore!=null?t.targetPerformanceScore:null,showGoalsOnDashboard:t.showGoalsOnDashboard!==!1,currentCoverage:t.currentCoverage??0,currentCited:t.currentCited??0,currentPerformanceScore:t.currentPerformanceScore??0,suggestedTargetCitationSharePct:t.suggestedTargetCitationSharePct??null,goalItems:os(t.goalItems)})}catch{On(null)}finally{Nn(!1)}}},[u]);c.useEffect(()=>{u&&Mn()},[u,Mn]);const Un=he.useCallback((t,n,i)=>{const o=Wn(t,n,i),a=Oe.get(t,o);if(a)return a;try{const p=localStorage.getItem(o);if(p){const A=JSON.parse(p);if(A&&typeof A.timestamp=="number"&&Date.now()-A.timestamp<=gn)return Oe.set(t,o,A.data,gn),A.data}}catch(p){console.warn("Failed to read cached AEO recommendations",p)}return null},[]),qn=he.useCallback((t,n,i,o)=>{const a=Wn(t,n,i);Oe.set(t,a,o,gn);try{localStorage.setItem(a,JSON.stringify({timestamp:Date.now(),data:o}))}catch(p){console.warn("Failed to write cached AEO recommendations",p)}},[]),Bi=t=>{if(t.length>=4)return t.slice(0,4);const n=[{title:"Expand coverage with new prompts",description:"Add 5-10 high-intent queries to improve AI Overview reach and citation opportunities."},{title:"Strengthen citation targets",description:"Create or refresh pages for your highest-volume queries to compete for citations."}
4,{title:"Boost mid‑funnel visibility",description:"Improve comparison and FAQ content to win citations for consideration-stage prompts."},{title:"Improve on‑page clarity",description:"Use concise answers, schema markup, and clear headings to help AI Overviews extract content."}],i=[...t];for(const o of n){if(i.length>=4)break;i.some(a=>a.title===o.title)||i.push(o)}return i.slice(0,4)},Qe=he.useCallback(async(t,n,i,o=!1)=>{if(!t||!u){xt("Skipping recommendations fetch - insufficient data",{hasMetrics:!!t,hasClientName:!!u});return}const a=u,p=$,A=o?null:Un(a,p,k);if(A){et(A);return}xt("Fetching recommendations for client:",a),bt(!0);try{const l=await K.post(`/api/generative-seo/${encodeURIComponent(a)}/recommendations`,{location:k,domainForContext:V||void 0,metrics:{totalPrompts:t.totalPrompts,promptsWithAiOverview:t.promptsWithAiOverview,promptsCited:t.promptsCited,coveragePercentage:t.coveragePercentage,citationPercentage:t.citationPercentage,newCitations:t.newCitations,lostCitations:t.lostCitations,totalAiOverviews:t.totalAiOverviews,totalCitations:t.totalCitations,clientCitations:t.clientCitations,avgPosition:t.avgPosition},prompts:(n||[]).slice(0,5).map(D=>({text:D.text,intent:D.intent,stage:D.stage,cited:D.cited})),historicalData:i.slice(0,5).map(D=>({date:D.date,clicks:D.clicks,impressions:D.impressions})),competitorMetrics:t.competitor_metrics,forceRefresh:o});xt("Recommendations API response:",l);const N=Array.isArray(l.recommendations)?l.recommendations:[],W=Bi(N.length>0?N:ce);W.length>0||ce.length===0?(xt("Setting recommendations:",W),et(W)):console.warn("Recommendations response is empty or invalid format:",l),qn(a,p,k,W)}catch(l){const N=l.message||"Unknown error";console.warn("Failed to fetch recommendations:",N)}finally{bt(!1)}},[u,V,$,k,Un,qn,ce]);c.useEffect(()=>{(async()=>{if(u)try{try{const n=await K.get(`/api/generative-seo/${encodeURIComponent(u)}/competitors`),i=[{value:"main",label:"You"}];n.competitors&&Array.isArray(n.competitors)&&n.competitors.forEach(o=>{if(o.urls&&o.urls.length>0){const a=o.urls[0].replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0];i.push({value:a,label:o.name||a})}}),bn(i)}catch(n){console.warn("Failed to fetch competitors:",n)}}catch(n){console.error("Error loading brands:",n)}})()},[u]),c.useEffect(()=>{(async()=>{var n,i,o,a;try{if(G.current?_(!0):U(!0),Pe(null),!u){U(!1);return}const p=k!=="default"?`&location=${encodeURIComponent(k)}`:"",A=g.length>0?`&sources=${encodeURIComponent(g.join(","))}&aggregate=average`:"",l=`/api/generative-seo/${encodeURIComponent(u)}/metrics?location=${encodeURIComponent(k)}${A}`,N=`/api/generative-seo/${encodeURIComponent(u)}/prompts?limit=1000&includeLargeFields=true&location=${encodeURIComponent(k)}`,W=`/api/generative-seo/${encodeURIComponent(u)}/historical?days=30${p}`,D=`/api/generative-seo/${encodeURIComponent(u)}/sentiment?location=${encodeURIComponent(k)}`,Q=`/api/generative-seo/${encodeURIComponent(u)}/heatmap?location=${encodeURIComponent(k)}`,xe=null,Re=Oe.get(u,gt(N)),we=Oe.get(u,gt(W)),Ce=Oe.get(u,gt(D)),ge=Oe.get(u,gt(Q)),_e=[];_e.push({key:"metrics",promise:K.get(l)}),Re||_e.push({key:"prompts",promise:K.get(N)}),we||_e.push({key:"historical",promise:K.get(W).catch(()=>[])}),Ce||_e.push({key:"sentiment",promise:K.get(D).catch(()=>null)}),ge||_e.push({key:"heatmap",promise:K.get(Q).catch(()=>null)});const Ee=await Promise.all(_e.map(x=>x.promise.then(ee=>({key:x.key,data:ee})).catch(ee=>({key:x.key,data:null,error:ee})))),se=new Map;se.set("metrics",xe),se.set("prompts",Re),se.set("historical",we||[]),se.set("sentiment",Ce),se.set("heatmap",ge),Ee.forEach(({key:x,data:ee})=>{if(ee!==void 0){se.set(x,ee);const ct=x==="metrics"?l:x==="prompts"?N:x==="historical"?W:x==="sentiment"?D:Q;Oe.set(u,gt(ct),ee)}});const R=hn(se.get("metrics")),ot=me(se.get("prompts")),j=me(se.get("historical")),z=se.get("sentiment"),O=se.get("heatmap");let Y={totalPrompts:R.total_prompts||0,promptsWithAiOverview:R.prompts_with_aio||0,promptsCited:R.prompts_cited||0,coveragePercentage:R.prompt_coverage||R.citation_coverage||0,citationPercentage:R.prompts_cited&&R.total_prompts?R.prompts_cited/R.total_prompts*100:0,newCitations:R.new_citations||0,lostCitations:R.lost_citations||0,totalAiOverviews:R.total_ai_overviews||0,totalCitations:R.total_citations||0,clientCitations:R.client_citations||0,totalClicks:((n=R.ai_traffic_summary)==null?void 0:n.total_clicks)||0,totalImpressions:((i=R.ai_traffic_summary)==null?void 0:i.total_impressions)||0,avgCtr:((o=R.ai_traffic_summary)==null?void 0:o.avg_ctr)||0,avgPosition:R.avg_position!==void 0&&R.avg_position!==null?R.avg_position:((a=R.ai_traffic_summary)==null?void 0:a.avg_position)!==void 0?R.ai_traffic_summary.avg_position:null,performance_score:R.performance_score,top_cited_pages:me(R.top_cited_pages),competitor_metrics:R.competitor_metrics||void 0,source_metrics:R.source_metrics||void 0,sources:R.sources||g,available_sources:R.available_sources||["google_aio"],source_mode:R.source_mode,aggregate:R.aggregate};if(Array.isArray(R.available_sources)&&R.available_sources.length>0&&v(R.available_sources),$!=="main"&&Y.competitor_metrics&&Y.competitor_metrics[$]){const x=Y.competitor_metrics[$],ee={...Y},ct={[V]:{total_citations:ee.clientCitations||0,cited_prompts:ee.promptsCited||0,coverage_percentage:ee.coveragePercentage||0,total_ai_overviews:ee.totalAiOverviews||0,avg_position:ee.avgPosition||0},...Object.fromEntries(Object.entries(ee.competitor_metrics||{}).filter(([Tt])=>Tt!==$))};Y={...Y,clientCitations:x.total_citations||0,promptsCited:x.cited_prompts||0,coveragePercentage:x.coverage_percentage||0,avgPosition:x.avg_position||0,competitor_metrics:ct}}const at=ot.map(x=>
4{const ee=x.citations?typeof x.citations=="string"?JSON.parse(x.citations):x.citations:[],ct=$==="main"?x.cited===1||x.cited===!0:ee.some(Tt=>(Tt.domain||Tt.url||"").toLowerCase().includes($.toLowerCase()));return{promptId:String(x.prompt_id??""),text:x.text,intent:x.intent,stage:x.stage,branded:As(x.branded),priority:parseFloat(x.priority??.5),hasAio:x.has_aio===1||x.has_aio===!0,cited:ct,overview_text:x.overview_text,citations:ee,paa_questions:x.paa_questions?typeof x.paa_questions=="string"?JSON.parse(x.paa_questions):x.paa_questions:void 0,organic_results:x.organic_results?typeof x.organic_results=="string"?JSON.parse(x.organic_results):x.organic_results:void 0,content_structure:x.content_structure?typeof x.content_structure=="string"?JSON.parse(x.content_structure):x.content_structure:void 0,related_queries:x.related_queries?typeof x.related_queries=="string"?JSON.parse(x.related_queries):x.related_queries:void 0,client_organic_position:x.client_organic_position||null,competitor_organic_positions:x.competitor_organic_positions?typeof x.competitor_organic_positions=="string"?JSON.parse(x.competitor_organic_positions):x.competitor_organic_positions:void 0,serp_features:x.serp_features?typeof x.serp_features=="string"?JSON.parse(x.serp_features):x.serp_features:void 0,citation_contexts:x.citation_contexts?typeof x.citation_contexts=="string"?JSON.parse(x.citation_contexts):x.citation_contexts:void 0,topic:Ss(x.topic,x.text)}}),Dt=j.map(x=>({date:x.date,clicks:x.cited_count||0,impressions:x.appearances||0}));if(z)try{const x=hn(z);X({...x,details:me(x.details),by_topic:me(x.by_topic),by_persona:me(x.by_persona)})}catch{console.warn("Sentiment data not available")}if(O)try{be(O)}catch{console.warn("Heatmap data not available")}m(Y),S(at),P(Dt),Pe(null),Y&&u?setTimeout(()=>{Qe(Y,at,Dt,!1)},100):console.warn("⚠️ Not fetching recommendations - missing data:",{hasMetrics:!!Y,hasClientName:!!u})}catch(p){console.error("API Error:",p),console.error("Error details:",{sentimentResponse:"error",heatmapResponse:"error"});const A=(p==null?void 0:p.message)||String(p),l=A==="Failed to fetch"||A.includes("NetworkError")||A.includes("Load failed")||!navigator.onLine;Pe(l?"Unable to load data. Please check your internet connection and try again.":`Unable to load data: ${A}`),m({totalPrompts:0,promptsWithAiOverview:0,promptsCited:0,coveragePercentage:0,citationPercentage:0,newCitations:0,lostCitations:0,totalAiOverviews:0,totalCitations:0,clientCitations:0,totalClicks:0,totalImpressions:0,avgCtr:0,avgPosition:0,top_cited_pages:[]}),S([])}finally{U(!1),_(!1)}})()},[u,V,$,k,Qe]);const Gn=c.useCallback(async t=>{var n,i,o,a;if(u){_(!0);try{const p=t.length>0?`&sources=${encodeURIComponent(t.join(","))}&aggregate=average`:"",A=`/api/generative-seo/${encodeURIComponent(u)}/metrics?location=${encodeURIComponent(k)}${p}`,l=hn(await K.get(A));let N={totalPrompts:l.total_prompts||0,promptsWithAiOverview:l.prompts_with_aio||0,promptsCited:l.prompts_cited||0,coveragePercentage:l.prompt_coverage||l.citation_coverage||0,citationPercentage:l.prompts_cited&&l.total_prompts?l.prompts_cited/l.total_prompts*100:0,newCitations:l.new_citations||0,lostCitations:l.lost_citations||0,totalAiOverviews:l.total_ai_overviews||0,totalCitations:l.total_citations||0,clientCitations:l.client_citations||0,totalClicks:((n=l.ai_traffic_summary)==null?void 0:n.total_clicks)||0,totalImpressions:((i=l.ai_traffic_summary)==null?void 0:i.total_impressions)||0,avgCtr:((o=l.ai_traffic_summary)==null?void 0:o.avg_ctr)||0,avgPosition:l.avg_position!==void 0&&l.avg_position!==null?l.avg_position:((a=l.ai_traffic_summary)==null?void 0:a.avg_position)!==void 0?l.ai_traffic_summary.avg_position:null,performance_score:l.performance_score,top_cited_pages:me(l.top_cited_pages),competitor_metrics:l.competitor_metrics||void 0,source_metrics:l.source_metrics||void 0,sources:l.sources||t,available_sources:l.available_sources||["google_aio"],source_mode:l.source_mode,aggregate:l.aggregate};if(Array.isArray(l.available_sources)&&l.available_sources.length>0&&v(l.available_sources),$!=="main"&&N.competitor_metrics&&N.competitor_metrics[$]){const W=N.competitor_metrics[$],D={...N},Q={[V]:{total_citations:D.clientCitations||0,cited_prompts:D.promptsCited||0,coverage_percentage:D.coveragePercentage||0,total_ai_overviews:D.totalAiOverviews||0,avg_position:D.avgPosition||0},...Object.fromEntries(Object.entries(D.competitor_metrics||{}).filter(([xe])=>xe!==$))};N={...N,clientCitations:W.total_citations||0,promptsCited:W.cited_prompts||0,coveragePercentage:W.coverage_percentage||0,avgPosition:W.avg_position||0,competitor_metrics:Q}}m(N)}catch(p){console.error("Metrics source refresh failed:",p)}finally{_(!1)}}},[u,k,$,V]),zi=c.useCallback(t=>{y(t),Gn(t)},[Gn]),rt=he.useRef($),on=he.useRef({metrics:null,prompts:[],historicalData:[],fetchRecommendations:()=>{}});he.useEffect(()=>{on.current={metrics:s,prompts:b,historicalData:w,fetchRecommendations:Qe}}
4,[s,b,w,Qe]);const qe=he.useRef($e);if(he.useEffect(()=>{qe.current=$e},[$e]),c.useEffect(()=>{const t=n=>{var A,l;if(((A=n.detail)==null?void 0:A.contextName)!==u)return;const{metrics:i,prompts:o,historicalData:a,fetchRecommendations:p}=on.current;i&&p&&p(i,o,a,!0),(l=qe.current)==null||l.call(qe)};return window.addEventListener("aeo-recommendations-refreshed",t),()=>window.removeEventListener("aeo-recommendations-refreshed",t)},[u]),c.useEffect(()=>{const t=n=>{var i;if(!(n.key!=="aeo-recommendations-refresh-requested"||n.newValue==null))try{const{contextName:o}=JSON.parse(n.newValue);if(o!==u)return;const{metrics:a,prompts:p,historicalData:A,fetchRecommendations:l}=on.current;a&&l&&l(a,p,A,!0),(i=qe.current)==null||i.call(qe),localStorage.removeItem("aeo-recommendations-refresh-requested")}catch{}};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[u]),c.useEffect(()=>{rt.current!==$&&s&&u&&!C?(xt("🔄 Brand changed from",rt.current,"to",$,"- refreshing recommendations"),Qe(s,b,w,!0),rt.current=$):rt.current===$&&!C&&(rt.current=$)},[$,k,s,b,w,u,C,Qe]),Jt||!L)return e.jsx(mi,{title:"AI Search Intelligence",hideHeader:Jt,children:Jt?e.jsx(d,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"400px",children:e.jsx(ze,{})}):e.jsx(d,{sx:{mt:2},children:e.jsx(ye,{severity:"info",children:"No Search Intelligence context available for this account. Please select or create a client context in settings to begin."})})});if(C&&!s)return e.jsx(d,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"400px",children:e.jsx(ze,{})});if(!s)return e.jsx(ye,{severity:"info",children:"No data available for the selected client and date range."});b.filter(t=>t.paa_questions&&t.paa_questions.length>0),b.filter(t=>t.organic_results&&t.organic_results.length>0),b.filter(t=>t.serp_features&&Object.values(t.serp_features).some(Boolean));const Fi=k!=="default"&&(s.totalAiOverviews===0||s.promptsCited===0&&s.totalPrompts>0);return e.jsxs(d,{sx:{p:{xs:1,sm:2,md:3},opacity:f?.72:1,transition:"opacity 0.2s ease",pointerEvents:f?"none":"auto"},children:[ie&&e.jsx(ye,{severity:"error",sx:{mb:2},onClose:()=>Pe(null),children:ie}),Fi&&e.jsxs(ye,{severity:"info",sx:{mb:2},children:[e.jsx(r,{variant:"subtitle2",gutterBottom:!0,children:"No data for this location yet"}),e.jsxs(r,{variant:"body2",paragraph:!0,sx:{mb:0},children:["Data for"," ",e.jsx("strong",{children:pn((Kn=L==null?void 0:L.locations)==null?void 0:Kn.find(t=>t.location===k))||k})," ","is collected when you run an ",e.jsx("strong",{children:"AI Overview check"})," with this location selected. Run a check from"," ",e.jsx(zt,{component:Xn,to:"/prompts",sx:{fontWeight:600},children:"Prompt Manager"})," ",'(e.g. "Re-run AI Checks"), or enable automatic collection in Settings.']})]}),e.jsxs(d,{sx:{display:"flex",flexDirection:{xs:"column",sm:"row"},justifyContent:"space-between",alignItems:{xs:"stretch",sm:"center"},gap:2,mb:3,maxWidth:"100%",minWidth:0},children:[e.jsxs(d,{sx:{minWidth:0},children:[e.jsx(r,{variant:"h3",component:"h1",fontWeight:"bold",children:"Answer Engine Optimization"}),(Qt||k!=="default")&&((Vn=L==null?void 0:L.locations)==null?void 0:Vn.length)&&e.jsxs(r,{variant:"body2",color:"text.secondary",sx:{mt:.5},children:["Viewing location:"," ",e.jsx("strong",{children:pn(L.locations.find(t=>t.location===k))||k}),Qt?" (single-location account)":" — All metrics, prompts, and runs below are for this location only."]})]}),e.jsxs(d,{sx:{display:"flex",flexWrap:"wrap",gap:2,alignItems:"center",minWidth:0},children:[_i&&e.jsxs(Se,{size:"small",sx:{minWidth:180},children:[e.jsx(Ae,{children:"View Brand"}),e.jsx(Ie,{value:$,label:"View Brand",onChange:t=>xi(t.target.value),children:Zt.map(t=>e.jsx(M,{value:t.value,children:t.label},t.value))})]}),(L==null?void 0:L.locations)&&L.locations.length>0&&!Qt&&e.jsxs(Se,{size:"small",sx:{minWidth:220},children:[e.jsx(Ae,{children:"Location"}),e.jsx(Ie,{value:k,label:"Location",onChange:t=>{const n=t.target.value;pi(n);const i=new URLSearchParams(H.search);n&&n!=="default"?i.set("location",n):i.delete("location");const o=i.toString();te(`${H.pathname}${o?`?${o}`:""}`,{replace:!0})},children:L.locations.map(t=>e.jsx(M,{value:t.location,children:pn(t)||t.location},t.location))})]}
4),(s==null?void 0:s.competitor_metrics)&&Object.keys(s.competitor_metrics).length>0&&e.jsx(je,{variant:"outlined",onClick:()=>gi(!Xt),size:"small",sx:{ml:1,minWidth:"140px"},children:Xt?"Hide Comparison":"Show Comparison"}),e.jsx(je,{variant:"outlined",color:"primary",startIcon:e.jsx(Yi,{}),onClick:()=>{if(!s||!b.length){alert("No data available to export. Please wait for data to load.");return}try{const t=new Date,n={start:t.toISOString().split("T")[0],end:t.toISOString().split("T")[0]},i={totalPrompts:s.totalPrompts||b.length||0,totalAiOverviews:s.totalAiOverviews||0,promptsCited:s.promptsCited||0,clientCitations:s.clientCitations||0,contextCitations:s.clientCitations||s.totalCitations||0,coveragePercentage:s.coveragePercentage||0,avgPosition:(s.avgPosition??null)!==null?s.avgPosition:0,competitor_metrics:s.competitor_metrics};ws({contextName:(L==null?void 0:L.name)||u||"Unknown Client",domain:Oi(),dateRange:n,metrics:i,prompts:b})}catch(t){console.error("Error generating CSV:",t),alert("Failed to generate CSV report. Please try again.")}},disabled:C||!s||!b.length,sx:{mr:1},children:"Export CSV"})]})]}),Z===E.overview&&e.jsxs(e.Fragment,{children:[e.jsx(gs,{loading:C&&!s,score:(Yn=s==null?void 0:s.performance_score)==null?void 0:Yn.score,level:(Jn=s==null?void 0:s.performance_score)==null?void 0:Jn.level,color:(Qn=s==null?void 0:s.performance_score)==null?void 0:Qn.color,coveragePct:s==null?void 0:s.coveragePercentage,clientCitations:s==null?void 0:s.clientCitations,totalCitations:s==null?void 0:s.totalCitations,answersFound:s==null?void 0:s.totalAiOverviews,brandDomain:$==="main"?V:$,sparkline:ji.performance,subtitle:s!=null&&s.performance_score?`${s.performance_score.level} visibility across selected answer engines.`:null,metricSources:g,availableMetricSources:h,onMetricSourcesChange:zi,metricsRefreshing:f}),$==="main"&&e.jsxs(d,{sx:{mb:3,mt:1},children:[e.jsxs(r,{variant:"h6",fontWeight:600,sx:{mb:.5},children:["Recommendations",e.jsx(r,{component:"span",variant:"caption",color:"text.secondary",sx:{ml:1,fontWeight:400},children:"Beta"})]}),e.jsx(r,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"Priority next steps from your latest answer-engine data."}),Yt?e.jsxs(d,{sx:{display:"flex",alignItems:"center",py:2},children:[e.jsx(ze,{size:22}),e.jsx(r,{variant:"body2",sx:{ml:2},children:"Loading recommendations…"})]}):Ln.length>0?e.jsx(J,{container:!0,spacing:2,children:Ln.map(t=>{const n=xn(t);return e.jsx(J,{item:!0,xs:12,md:6,children:e.jsxs(d,{sx:{p:2,borderLeft:"3px solid",borderColor:"primary.main",bgcolor:"action.hover",borderRadius:1,height:"100%",display:"flex",flexDirection:"column"},children:[e.jsxs(d,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:1,mb:1},children:[e.jsx(r,{variant:"subtitle1",fontWeight:600,sx:{flex:1,minWidth:0},children:t.title}),e.jsx(je,{size:"small",variant:"outlined",onClick:()=>Ni(t),sx:{flexShrink:0,whiteSpace:"nowrap"},children:"Mark as complete"})]}),e.jsx(r,{variant:"body2",color:"text.secondary",sx:{flex:1},children:t.description})]})},`rec-${n}`)})}):ce.length>0?e.jsx(r,{variant:"body2",color:"text.secondary",children:"You've marked all current recommendations complete. New ones appear after the next refresh in Settings."}):e.jsx(r,{variant:"body2",color:"text.secondary",children:"No recommendations yet. Collect answer-engine data or refresh recommendations in Settings."})]}),e.jsx(ys,{sourceMetrics:s==null?void 0:s.source_metrics,loading:C&&!s}),e.jsx(is,{contextName:u,variant:"compact"}),e.jsx(ni,{contextName:u,variant:"compact",onOpenPersonas:Pn,onManagePersonas:kn})]}),Z===E.overview&&(B==null?void 0:B.showGoalsOnDashboard)&&e.jsx(Ge,{title:"Goals",children:Ri?e.jsx(d,{display:"flex",justifyContent:"center",py:2,children:e.jsx(ze,{size:28})}):B?e.jsxs(J,{container:!0,spacing:3,sx:{mb:2},children:[(B.targetCitationSharePct!=null||B.suggestedTargetCitationSharePct!=null)&&e.jsx(J,{item:!0,xs:12,md:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsx(r,{color:"textSecondary",gutterBottom:!0,children:"Citation share"}),e.jsxs(r,{variant:"h5",children:[(B.currentCoverage??0).toFixed(1),"% → ",B.targetCitationSharePct!=null?`${B.targetCitationSharePct}% target`:`suggested ${B.suggestedTargetCitationSharePct??25}%`]}),B.targetCitationSharePct!=null&&(()=>{const t=B.targetCitationSharePct,n=B.currentCoverage??0,i=t-n;let o="on_track";return n>=t?o="on_track":i<=10||n>=t*.85?o="at_risk":o="behind",e.jsx(q,{sx:{mt:1},label:o==="on_track"?"On track":o==="at_risk"?"At risk":"Behind",color:o==="on_track"?"success":o==="at_risk"?"warning":"error",size:"small",variant:"outlined"})})()]})})}),B.targetCitedCount!=null&&e.jsx(J,{item:!0,xs:12,md:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsx(r,{color:"textSecondary",gutterBottom:!0,children:"Cited count"}),e.jsxs(r,{variant:"h5",children:[B.currentCited," / ",B.targetCitedCount," target"]}),B.currentCited>=(B.targetCitedCount??0)?e.jsx(q,{sx:{mt:1},label:"On track",color:"success",size:"small",variant:"outlined"}):e.jsx(q,{sx:{mt:1},label:"Behind",color:"warning",size:"small",variant:"outlined"})]})})}),B.targetPerformanceScore!=null&&e.jsx(J,{item:!0,xs:12,md:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsx(r,{color:"textSecondary",gutterBottom:!0,children:"Performance score"}),e.jsxs(r,{variant:"h5",children:[B.currentPerformanceScore," / ",B.targetPerformanceScore," target"]}),B.currentPerformanceScore>=(B.targetPerformanceScore??0)?e.jsx(q,{sx:{mt:1},label:"On track",color:"success",size:"small",variant:"outlined"}):e.jsx(q,{sx:{mt:1},label:"Behind",color:"warning",size:"small",variant:"outlined"})]})})}),(B.goalItems??[]).filter(t=>{var n;return t.kind==="text"&&!!((n=t.text)!=null&&n.trim())}).map(t=>e.jsx(J,{item:!0,xs:12,md:6,children:e.jsx(le,{variant:"outlined",children:e.jsxs(de,{children:[e.jsx(r,{color:"textSecondary",gutterBottom:!0,children:"Custom goal"}),e.jsx(r,{variant:"body1",sx:{whiteSpace:"pre-wrap"},children:t.text.trim()})]})})},t.id)),!B.targetCitationSharePct&&B.suggestedTargetCitationSharePct==null&&B.targetCitedCount==null&&B.targetPerformanceScore==null&&!(B.goalItems??[]).some(t=>{var n;return t.kind==="text"&&((n=t.text)==null?void 0:n.trim())})&&e.jsx(J,{item:!0,xs:12,children:e.jsx(r,{variant:"body2",color:"text.secondary",children:"Set goals in Settings to see progress here."})})]}):e.jsx(r,{variant:"body2",color:"text.secondary",children:"Unable to load goals."})}),Z===E.overview&&(s.newCitations>0||s.lostCitations>
40)&&e.jsx(Ge,{title:"Citation Changes",children:e.jsxs(J,{container:!0,spacing:3,sx:{mb:4},children:[e.jsx(J,{item:!0,xs:12,sm:6,md:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsxs(d,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(r,{color:"textSecondary",gutterBottom:!0,children:"New Citations"}),e.jsx(Ne,{title:"Number of prompts that are cited in the most recent data but were NOT cited in the previous data collection period. Requires historical data for comparison.",children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(lt,{size:"small",children:e.jsx(Fe,{fontSize:"small",color:"action"})})})})})})})]}),e.jsx(r,{variant:"h4",component:"div",color:"success.main",children:s.newCitations||0}),e.jsx(r,{variant:"body2",color:"textSecondary",children:"vs previous 30 days"})]})})}),e.jsx(J,{item:!0,xs:12,sm:6,md:6,children:e.jsx(le,{children:e.jsxs(de,{children:[e.jsxs(d,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(r,{color:"textSecondary",gutterBottom:!0,children:"Lost Citations"}),e.jsx(Ne,{title:"Number of prompts that were cited in the previous data collection period but are NO LONGER cited in the most recent period. Requires historical data for comparison.",children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(lt,{size:"small",children:e.jsx(Fe,{fontSize:"small",color:"action"})})})})})})})]}),e.jsx(r,{variant:"h4",component:"div",color:"error.main",children:s.lostCitations||0}),e.jsx(r,{variant:"body2",color:"textSecondary",children:"vs previous 30 days"})]})})})]})}),Z===E.insights&&e.jsxs(e.Fragment,{children:[e.jsx(ni,{contextName:u,variant:"compact",onOpenPersonas:Pn,onManagePersonas:kn}),e.jsx(Ge,{title:"Enhanced Insights",children:e.jsx(J,{container:!0,spacing:3,sx:{mb:4},children:e.jsx(J,{item:!0,xs:12,md:12,children:e.jsx(le,{sx:{height:"100%",display:"flex",flexDirection:"column"},children:e.jsxs(de,{sx:{flex:1,display:"flex",flexDirection:"column"},children:[e.jsxs(d,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:1,flexWrap:"wrap",sx:{mb:1},children:[e.jsxs(d,{display:"flex",alignItems:"center",gap:1,children:[e.jsx(r,{variant:"h6",gutterBottom:!0,sx:{mb:0},children:"AI Overview Sentiment Analysis"}),e.jsx(Ne,{title:"Uses LLM sentiment after Score with AI; otherwise lexical fallback. Citation-source audit checks whether influential third-party pages mention your brand. Persona rollups include synthetic chat sentiment.",children:e.jsx(lt,{size:"small",children:e.jsx(Fe,{fontSize:"small",color:"action"})})})]}),e.jsxs(oe,{direction:"row",spacing:1,flexWrap:"wrap",children:[e.jsx(je,{size:"small",variant:"outlined",disabled:pe||!u,onClick:fi,children:pe?"Scoring…":"Score with AI"}),e.jsx(je,{size:"small",variant:"outlined",disabled:We||!u,onClick:vi,children:We?"Auditing…":"Audit citation sources"})]})]}),Me&&e.jsx(r,{variant:"body2",color:"text.secondary",sx:{mb:1},children:Me}),e.jsx(He,{sx:{mb:2}}),T?(()=>{const t=T.details||[],n=t.filter(j=>j.sentiment_label==="positive").sort((j,z)=>z.sentiment_score-j.sentiment_score),i=t.filter(j=>j.sentiment_label==="neutral"),o=t.filter(j=>j.sentiment_label==="negative").sort((j,z)=>j.sentiment_score-z.sentiment_score),a=T.overall.positive||0,p=T.overall.neutral||0,A=T.overall.negative||0,l=a+p+A,N=l>0?Math.round(a/l*100):0,W=l>0?Math.round(p/l*100):0,D=l>0?Math.round(A/l*100):0,Q=T.overall.avg_sentiment_score,xe=Q===void 0||Number.isNaN(Q)?null:Q>.15?"net-positive":Q<-.15?"net-negative":"roughly neutral",Re=j=>j.length===0?{cite:0,pos:0,brand:0}:{cite:j.reduce((z,O)=>z+(O.citation_count||0),0)/j.length,pos:j.reduce((z,O)=>z+(O.avg_position||0),0)/j.length,brand:j.filter(z=>z.brand_mentioned).length},we=Re(n),Ce=Re(i),ge=Re(o),_e=j=>{const z=[{label:"pricing/value",re:/(price|pricing|cost|expensive|cheap|value|worth)/i},{label:"reviews / complaints",re:/(review|reviews|complaint|problems|issues|bad|worst|avoid|scam)/i},{label:"trust / reputation",re:/(trust|reliable|reputation|legit|fraud)/i},{label:"alternatives / comparisons",re:/(vs|versus|alternative|compare|c
4omparison|better than)/i},{label:"support / warranty",re:/(warranty|support|customer service|refund|return)/i}];for(const O of z)if(O.re.test(j))return O.label;return"other"},Ee={};o.forEach(j=>{const z=_e(j.prompt_text||"");Ee[z]||(Ee[z]={count:0,samples:[]}),Ee[z].count+=1,Ee[z].samples.length<3&&Ee[z].samples.push(j.prompt_text||"")});const se=Object.entries(Ee).map(([j,z])=>({label:j,...z})).sort((j,z)=>z.count-j.count),R=(j,z)=>j.length<=z?j:`${j.slice(0,z)}…`,ot=({rows:j})=>{const z=[...j].sort((O,Y)=>{const at=Array.isArray(O.response_negative_cues)&&O.response_negative_cues.length>0,Dt=Array.isArray(Y.response_negative_cues)&&Y.response_negative_cues.length>0;if(at!==Dt)return at?-1:1;const x=Array.isArray(O.response_positive_cues)&&O.response_positive_cues.length>0,ee=Array.isArray(Y.response_positive_cues)&&Y.response_positive_cues.length>0;return x!==ee?x?-1:1:(Y.citation_count??0)!==(O.citation_count??0)?(Y.citation_count??0)-(O.citation_count??0):(O.avg_position||999)-(Y.avg_position||999)});return e.jsx(ht,{sx:{maxHeight:320},children:e.jsxs(mt,{size:"small",stickyHeader:!0,children:[e.jsx(ut,{children:e.jsxs(fe,{children:[e.jsx(I,{sx:{fontWeight:600},children:"Tracked prompt"}),e.jsx(I,{sx:{fontWeight:600,minWidth:220},children:"Negative language in response/sources"}),e.jsx(I,{align:"right",sx:{fontWeight:600,whiteSpace:"nowrap"},children:"Score"}),e.jsx(I,{align:"right",sx:{fontWeight:600},children:"Citations"}),e.jsx(I,{align:"right",sx:{fontWeight:600},children:"Avg pos."}),e.jsx(I,{sx:{fontWeight:600},children:"Brand in AIO"})]})}),e.jsx(pt,{children:z.map(O=>e.jsxs(fe,{children:[e.jsxs(I,{children:[e.jsx(Ne,{title:O.prompt_text||"",placement:"top-start",children:e.jsx(d,{children:O.prompt_id?e.jsx(zt,{component:"button",type:"button",variant:"body2",onClick:()=>jn(O.prompt_id),sx:{maxWidth:420,display:"inline-block",fontWeight:600,textAlign:"left",verticalAlign:"baseline",cursor:"pointer",border:"none",background:"none",padding:0,font:"inherit",color:"primary.main"},underline:"hover",children:R(O.prompt_text||"—",140)}):e.jsx(r,{variant:"body2",sx:{maxWidth:420},children:R(O.prompt_text||"—",140)})})}),O.overview_snippet?e.jsxs(r,{variant:"caption",color:"text.secondary",display:"block",sx:{mt:.5},children:["AIO excerpt: ",R(O.overview_snippet,160)]}):null]}),e.jsx(I,{sx:{verticalAlign:"top"},children:Array.isArray(O.response_negative_cues)&&O.response_negative_cues.length>0?e.jsx(d,{sx:{display:"flex",flexWrap:"wrap",gap:.5},children:O.response_negative_cues.slice(0,5).map(Y=>e.jsx(q,{size:"small",color:"error",variant:"outlined",label:Y},`${O.prompt_id}-${Y}`))}):null}),e.jsx(I,{align:"right",children:e.jsx(r,{variant:"body2",color:O.sentiment_label==="positive"?"success.main":O.sentiment_label==="negative"?"error.main":"text.secondary",children:O.sentiment_score.toFixed(2)})}),e.jsx(I,{align:"right",children:O.citation_count??"—"}),e.jsx(I,{align:"right",children:O.avg_position?O.avg_position.toFixed(1):"—"}),e.jsx(I,{children:O.brand_mentioned?e.jsx(q,{size:"small",color:"primary",variant:"outlined",label:"Yes"}):e.jsx(q,{size:"small",variant:"outlined",label:"No"})})]},O.prompt_id))})]})})};return e.jsxs(e.Fragment,{children:[e.jsxs(d,{sx:{display:"flex",flexWrap:"wrap",gap:2,justifyContent:"space-around",mb:2},children:[e.jsxs(d,{sx:{textAlign:"center",minWidth:72},children:[e.jsx(r,{variant:"h4",color:"success.main",children:a}),e.jsx(r,{variant:"body2",color:"textSecondary",children:"Positive"})]}),e.jsxs(d,{sx:{textAlign:"center",minWidth:72},children:[e.jsx(r,{variant:"h4",color:"textSecondary",children:p}),e.jsx(r,{variant:"body2",color:"textSecondary",children:"Neutral"})]}),e.jsxs(d,{sx:{textAlign:"center",minWidth:72},children:[e.jsx(r,{variant:"h4",color:"error.main",children:A}),e.jsx(r,{variant:"body2",color:"textSecondary",children:"Negative"})]}),xe&&Q!==void 0&&!Number.isNaN(Q)&&e.jsxs(d,{sx:{textAlign:"center",minWidth:100},children:[e.jsx(r,{variant:"h4",color:"primary",children:Q.toFixed(2)}),e.jsxs(r,{variant:"body2",color:"textSecondary",children:["Avg. score (",xe,")"]})]})]}),(T.by_topic||[]).length>0&&e.jsxs(d,{sx:{mb:2},children:[e.jsx(r,{variant:"subtitle2",gutterBottom:!0,children:"By topic"}),e.jsx(oe,{direction:"row",flexWrap:"wrap",gap:1,children:(T.by_topic||[]).slice(0,8).map(j=>e.jsx(q,{size:"small",label:`${j.key}: ${j.avg_sentiment_score.toFixed(2)} (${j.count})`,variant:"outlined"},j.key))})]}),(T.by_persona||[]).length>0&&e.jsxs(d,{sx:{mb:2},children:[e.jsx(r,{variant:"subtitle2",gutterBottom:!0,children:"By persona"}),e.jsx(oe,{direction:"row",flexWrap:"wrap",gap:1,children:(T.by_persona||[]).slice(0,8).map(j=>e.jsx(q,{size:"small",color:"primary",label:`${j.key}: ${j.avg_sentiment_score.toFixed(2)} (${j.count})`,variant:"outlined"},j.key))})]}),e.jsxs(oe,{spacing:.75,sx:{mb:2},children:[e.jsxs(d,{sx:{display:"flex",alignItems:"center",gap:1},children:[e.jsxs(r,{variant:"caption",color:"success.main",sx:{width:72},children:[N,"%"]}),e.jsx(dn,{variant:"determinate",value:N,sx:{flex:1,height:8,borderRadius:1,bgcolor:"grey.200","& .MuiLinearProgress-bar":{bgcolor:"success.main"}}})]}),e.jsxs(d,{sx:{display:"flex",alignItems:"center",gap:1},children:[e.jsxs(r,{variant:"caption",color:"text.secondary",sx:{width:72},children:[W,"%"]}),e.jsx(dn,{variant:"determinate",value:W,sx:{flex:1,height:8,borderRadius:1,bgcolor:"grey.200","& .MuiLinearProgress-bar":{bgcolor:"grey.500"}}})]}),e.jsxs(d,{sx:{display:"flex",alignItems:"center",gap:1},children:[e.jsxs(r,{variant:"caption",color:"error.main",sx:{width:72},children:[D,"%"]}),e.jsx(dn,{variant:"determinate",value:D,sx:{flex:1,height:8,borderRadius:1,bgcolor:"grey.200","& .MuiLinearProgress-bar":{bgcolor:"error.main"}}})]})]}),e.jsxs(d,{sx:{mt:2,p:2,bgcolor:"grey.50",borderRadius:1},children:[e.jsx(r,{variant:"subtitle2",gutterBottom:!0,color:"primary",children:"Analysis overview"}),e.jsxs(oe,{spacing:1,children:[e.jsxs(r,{variant:"body2",color:"textSecondary",children:[e.jsx("strong",{children:l})," tracked prompts with an AI Overview in this location were scored (one latest run per prompt). Negative/neutral/positive buckets are categorized from lexical cue language in the ",e.jsx("strong",{children:"AI Overview response text"}),"plus citation source context, and the exact matched negative cue phrases are shown in the table."]}),l===0&&b.some(j=>j.hasAio)&&e.jsxs(r,{variant:"body2",color:"textSecondary",sx:{mt:1},children:["Your prompts show AI Overviews, but stored overview text was missing or filtered for this view. Run ",e.jsx("strong",{children:"Re-run AI checks"})," from Prompt settings so overview copy is saved, or confirm the location filter matches where checks were run."]}),e.jsxs(r,{variant:"body2",color:"textSecondary",children:["Mix: ",a," positive (",N,"%), ",p," neutral (",W,"%), ",A," negative (",D,"%)."]}),e.jsxs(r,{variant:"body2",color:"textSecondary",children:["Brand surfaced in the AI Overview text or citations:"," ",e.jsx("strong",{children:t.filter(j=>j.brand_mentioned).length})," of ",l," prompts (",l?Math.round(t.filter(j=>j.brand_mentioned).length/l*100):0,"%)."]}),e.jsx(r,{variant:"body2",color:"textSecondary",children:a>A?"Framing is net-positive in this sample. Focus on turning neutrals into positives with proof and differentiators.":A>a?"Framing trends negative in this sample. Prioritize trust, comparisons, and objection-handling content.":"Framing is mixed. Strengthen evidence-rich pages so neutrals shift positive."})]})]}),e.jsxs(d,{sx:{mt:2,p:2,bgcolor:"success.lighter",borderRadius:1},children:[e.jsxs(r,{variant:"subtitle2",gutterBottom:!0,color:"success.dark",children:["Positive prompts (",n.length,")"]}),e.jsxs(r,{variant:"body2",color:"textSecondary",sx:{mb:1},children:["Avg. citations in overview: ",e.jsx("strong",{children:we.cite.toFixed(1)}),", avg. citation position:"," ",e.jsx("strong",{children:we.pos>0?we.pos.toFixed(1):"—"}),".                           Brand in AIO:"," ",e.jsx("strong",{children:n.length===0?"—":`${we.brand}/${n.length}`}),". Strong alignment with intent—keep publishing answer-first copy, reviews, and differentiators the model can quote."]}),n.length>0&&e.jsxs(Ft,{disableGutters:!0,elevation:0,sx:{bgcolor:"transparent","&:before":{display:"none"}},children:[e.jsx(Ht,{expandIcon:e.jsx(dt,{}),children:e.jsxs(r,{variant:"subtitle2",children:["View all positive prompts (",n.length,")"]})}),e.jsx(Mt,{sx:{px:0},children:e.jsx(ot,{rows:n})})]})]}),e.jsxs(d,{sx:{mt:2,p:2,bgcolor:"warning.lighter",borderRadius:1},children:[e.jsxs(r,{variant:"subtitle2",gutterBottom:!0,color:"warning.dark",children:["Neutral prompts (",i.length,")"]}),e.jsxs(r,{variant:"body2",color:"textSecondary",sx:{mb:1},children:["Avg. citations: ",e.jsx("strong",{children:Ce.cite.toFixed(1)}),", avg. position:"," ",e.jsx("strong",{children:Ce.pos>0?Ce.pos.toFixed(1):"—"}),".                           Brand in AIO:"," ",e.jsx("strong",{children:i.length===0?"—":`${Ce.brand}/${i.length}`}
4),". Add comparisons, benefit-led FAQs, and clearer CTAs so informational summaries become persuasive."]}),i.length>0&&e.jsxs(Ft,{disableGutters:!0,elevation:0,sx:{bgcolor:"transparent","&:before":{display:"none"}},children:[e.jsx(Ht,{expandIcon:e.jsx(dt,{}),children:e.jsxs(r,{variant:"subtitle2",children:["View neutral prompts (",Math.min(i.length,40)," shown)"]})}),e.jsx(Mt,{sx:{px:0},children:e.jsx(ot,{rows:i.slice(0,40)})})]})]}),e.jsxs(d,{sx:{mt:2,p:2,bgcolor:"error.lighter",borderRadius:1},children:[e.jsxs(r,{variant:"subtitle2",gutterBottom:!0,color:"primary",children:["Negative prompts (",o.length,")"]}),o.length===0?e.jsx(r,{variant:"body2",color:"textSecondary",children:"No negative prompts in this sample."}):e.jsxs(e.Fragment,{children:[e.jsxs(r,{variant:"body2",color:"textSecondary",sx:{mb:1},children:["Avg. citations: ",e.jsx("strong",{children:ge.cite.toFixed(1)}),", avg. citation position:"," ",e.jsx("strong",{children:ge.pos>0?ge.pos.toFixed(1):"—"}),". Brand in AIO:"," ",e.jsxs("strong",{children:[ge.brand,"/",o.length]}),".",ge.brand>0?` ${ge.brand} of ${o.length} negative prompts mention or cite your brand in the overview; the rest read as category-level.`:" None of these prompts show your brand in the overview text or citations—treat them as category-risk signals."]}),se.length>0&&e.jsx(d,{sx:{display:"flex",flexWrap:"wrap",gap:1,mb:1.5},children:se.map(j=>e.jsx(q,{size:"small",variant:"outlined",color:"error",label:`${j.label}: ${j.count}`},j.label))}),e.jsxs(r,{variant:"body2",color:"textSecondary",sx:{mb:1},children:["Top themes by ",e.jsx("strong",{children:"search query"})," topic (for prioritizing content ideas)—not the sentiment score, which uses overview text:"," ",se.slice(0,5).map(j=>`${j.label} (${j.count}, e.g. “${R(j.samples[0]||"",48)}”)`).join(" · "),"."]}),e.jsx(r,{variant:"body2",color:"textSecondary",sx:{mb:1.5},children:"Address the highest-count theme with dedicated landing content, FAQs, and trust assets so the AI Overview has better passages to cite."}),e.jsxs(Ft,{defaultExpanded:!0,disableGutters:!0,elevation:0,sx:{"&:before":{display:"none"}},children:[e.jsx(Ht,{expandIcon:e.jsx(dt,{}),children:e.jsxs(r,{variant:"subtitle2",children:["View all negative prompts (",o.length,")"]})}),e.jsx(Mt,{sx:{px:0},children:e.jsx(ot,{rows:o})})]})]})]})]})})():e.jsxs(ye,{severity:"info",children:["No sentiment scored yet. Use ",e.jsx("strong",{children:"Score with AI"})," after you have AI Overview or engine answers. Persona sentiment also appears above after you run synthetic chats."]})]})})})})})]}),Z===E.prompts&&e.jsx(Ge,{title:"Tracked Prompts & AI Overview Details",children:e.jsx(le,{children:e.jsxs(de,{sx:{p:{xs:2,sm:3}},children:[e.jsx(r,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"Showing tracked prompts with AI Overview text and citation sources."}),e.jsx(ei,{size:"small",fullWidth:!0,label:"Search prompts",placeholder:"Search by prompt text...",value:tn,onChange:t=>In(t.target.value),sx:{mb:2}}),e.jsxs(oe,{direction:{xs:"column",sm:"row"},spacing:{xs:1.5,sm:2},flexWrap:"wrap",useFlexGap:!0,sx:{mb:2.5},children:[e.jsxs(Se,{size:"small",sx:{minWidth:180},children:[e.jsx(Ae,{children:"Type"}),e.jsxs(Ie,{label:"Type",value:St,onChange:t=>wn(String(t.target.value)),children:[e.jsx(M,{value:"all",children:"All types"}),Ai.map(t=>e.jsx(M,{value:t,children:t.replace(/_/g," ")},t))]})]}),e.jsxs(Se,{size:"small",sx:{minWidth:160},children:[e.jsx(Ae,{children:"Funnel stage"}),e.jsxs(Ie,{label:"Funnel stage",value:At,onChange:t=>Cn(String(t.target.value)),children:[e.jsx(M,{value:"all",children:"All stages"}),Ii.map(t=>e.jsx(M,{value:t,children:t},t))]})]}),e.jsxs(Se,{size:"small",sx:{minWidth:170},children:[e.jsx(Ae,{children:"Branding"}),e.jsxs(Ie,{label:"Branding",value:It,onChange:t=>_n(t.target.value),children:[e.jsx(M,{value:"all",children:"All"}),e.jsx(M,{value:"branded",children:"Branded"}),e.jsx(M,{value:"unbranded",children:"Unbranded"})]})]}),e.jsxs(Se,{size:"small",sx:{minWidth:190},children:[e.jsx(Ae,{children:"Answered"}),e.jsxs(Ie,{label:"Answered",value:kt,onChange:t=>Sn(t.target.value),children:[e.jsx(M,{value:"all",children:"All"}),e.jsx(M,{value:"with",children:mn(!0)}),e.jsx(M,{value:"without",children:mn(!1)})]})]}),e.jsxs(Se,{size:"small",sx:{minWidth:160},children:[e.jsx(Ae,{children:"Citation"}
4),e.jsxs(Ie,{label:"Citation",value:$t,onChange:t=>An(t.target.value),children:[e.jsx(M,{value:"all",children:"All"}),e.jsx(M,{value:"cited",children:un(!0)}),e.jsx(M,{value:"not_cited",children:un(!1)})]})]}),e.jsx(je,{size:"small",variant:"text",onClick:()=>{In(""),wn("all"),Cn("all"),_n("all"),Sn("all"),An("all")},children:"Clear filters"})]}),e.jsxs(r,{variant:"caption",color:"text.secondary",sx:{display:"block",mb:1.5},children:["Showing ",Ot.length," unique prompts (",Rt.length," matching records) of ",b.length," total records"]}),b.length===0?e.jsx(r,{variant:"body2",color:"text.secondary",children:"No prompts available for this client/location yet."}):e.jsxs(d,{sx:{maxHeight:680,overflowY:"auto",pr:.5},children:[Ot.map(({prompt:t,count:n})=>{const i=String(t.promptId),o=Ve!=null&&String(Ve)===i;return e.jsxs(Ft,{id:`aeo-prompt-accordion-${i}`,expanded:o,onChange:(a,p)=>{p?yn(i):o&&yn(null)},disableGutters:!0,sx:{mb:1.5,border:"1px solid",borderColor:"divider",borderRadius:1,"&:before":{display:"none"}},children:[e.jsx(Ht,{expandIcon:e.jsx(dt,{}),children:e.jsxs(d,{sx:{width:"100%"},children:[e.jsx(r,{variant:"subtitle2",sx:{pr:2,mb:1},children:t.text}),e.jsxs(d,{sx:{mt:.5,display:"flex",gap:1,flexWrap:"wrap"},onClick:a=>a.stopPropagation(),onFocus:a=>a.stopPropagation(),children:[e.jsx(q,{size:"small",color:t.hasAio?"success":"default",label:mn(!!t.hasAio)}),e.jsx(q,{size:"small",color:t.cited?"primary":"default",label:un(!!t.cited)}),n>1&&e.jsx(q,{size:"small",color:"warning",label:`${n} duplicates`}),e.jsx(q,{size:"small",color:t.branded===!0?"secondary":"default",label:t.branded===!0?"Branded":"Unbranded"}),e.jsx(q,{size:"small",label:String(t.stage||"unknown")}),e.jsx(q,{size:"small",label:String(t.intent||"unknown").replace(/_/g," ")})]})]})}),e.jsxs(Mt,{sx:{pt:.5,pb:2},children:[e.jsx(r,{variant:"subtitle2",sx:{mb:1},children:"AI answer"}),e.jsx(Be,{variant:"outlined",sx:{p:2,mb:2.5,bgcolor:"grey.50"},children:e.jsx(cs,{content:t.overview_text||"No answer text captured for this prompt yet."})}),e.jsx(r,{variant:"subtitle2",sx:{mb:1},children:"Sources"}),t.citations&&t.citations.length>0?e.jsx(oe,{spacing:1.25,children:t.citations.map((a,p)=>e.jsxs(Be,{variant:"outlined",sx:{p:1.5},children:[e.jsx(r,{variant:"body2",fontWeight:600,children:a.title||a.domain||a.url||`Source ${p+1}`}),a.snippet&&e.jsx(r,{variant:"body2",color:"text.secondary",sx:{mt:.5},children:a.snippet}),(a.url||a.domain)&&e.jsx(r,{variant:"caption",color:"text.secondary",sx:{display:"block",mt:.5},children:a.url||a.domain})]},`${t.promptId}-citation-${p}`))}):e.jsx(r,{variant:"body2",color:"text.secondary",children:"No source citations captured yet."})]})]},i)}),Rt.length===0&&e.jsx(r,{variant:"body2",color:"text.secondary",sx:{py:2},children:"No prompts match the selected filters."})]})]})})}),Z===E.serp&&e.jsxs(d,{sx:{mb:3},children:[e.jsxs(Be,{sx:{p:3,mb:2},children:[e.jsx(r,{variant:"h6",sx:{mb:1.5},children:"Our pages"}),s.top_cited_pages&&s.top_cited_pages.length>0?e.jsx(ht,{sx:{overflowX:"auto",WebkitOverflowScrolling:"touch"},children:e.jsxs(mt,{sx:{minWidth:{xs:300,sm:"auto"},"& .MuiTableCell-root":{fontSize:{xs:"0.75rem",sm:"0.875rem"},padding:{xs:"8px 4px",sm:"16px"}}},children:[e.jsx(ut,{children:e.jsxs(fe,{children:[e.jsx(I,{children:"URL"}),e.jsx(I,{children:"Cited Section"}),e.jsx(I,{children:"Referenced in prompts"}),e.jsx(I,{align:"right",children:"Citations"})]})}),e.jsx(pt,{children:s.top_cited_pages.map((t,n)=>{const i=t.url.indexOf("#"),o=i!==-1?t.url.substring(0,i):t.url,a=i!==-1?t.url.substring(i+1):"";let p="";if(a){const W=a.match(/:~:text=(.+)/);W?p=decodeURIComponent(W[1]).replace(/,/g," ... ").replace(/-/g," – "):p=decodeURIComponent(a).replace(/[-_]/g," ")}const A=qt(t.url),l=qt(o),N=Rn.get(A)||Rn.get(l)||[];return e.jsxs(fe,{children:[e.jsx(I,{sx:{maxWidth:360,minWidth:0},children:e.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",style:{color:"#1976d2",wordBreak:"break-all"},children:o})}),e.jsx(I,{sx:{maxWidth:300,minWidth:0},children:p?e.jsxs(r,{variant:"body2",sx:{fontStyle:"italic",color:"text.secondary",fontSize:"inherit"},children:["“",p,"”"]}
4):e.jsx(r,{variant:"body2",sx:{color:"text.disabled",fontSize:"inherit"},children:"—"})}),e.jsx(I,{sx:{maxWidth:280,minWidth:0,verticalAlign:"top"},children:N.length>0?e.jsx(oe,{spacing:.75,alignItems:"flex-start",children:N.map(W=>{const D=W.text.length>96?`${W.text.slice(0,96)}…`:W.text;return e.jsx(Ne,{title:W.text,placement:"top-start",children:e.jsx(zt,{component:"button",type:"button",variant:"body2",onClick:()=>jn(W.promptId),sx:{display:"inline-block",textAlign:"left",wordBreak:"break-word",cursor:"pointer",border:"none",background:"none",padding:0,font:"inherit",color:"primary.main",lineHeight:1.35},underline:"hover",children:D})},W.promptId)})}):e.jsx(r,{variant:"body2",sx:{color:"text.disabled",fontSize:"inherit"},children:"—"})}),e.jsx(I,{align:"right",children:t.citation_count})]},n)})})]})}):e.jsx(r,{variant:"body2",color:"text.secondary",children:"No cited pages found yet."})]}),e.jsxs(Be,{sx:{p:3},children:[e.jsxs(d,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:1.5},children:[e.jsx(r,{variant:"h6",children:"Top sources"}),Ye.length>10&&e.jsx(je,{size:"small",onClick:()=>bi(t=>!t),children:nn?"Show less":`Show more (${Ye.length-10} more)`})]}),Ye.length>0?e.jsx(ht,{children:e.jsxs(mt,{size:"small",children:[e.jsx(ut,{children:e.jsxs(fe,{children:[e.jsx(I,{sx:{width:48},"aria-label":"Expand"}),e.jsx(I,{children:"Domain"}),e.jsx(I,{align:"right",children:"Prompts with source"}),e.jsx(I,{align:"right",children:"Total citations"})]})}),e.jsx(pt,{children:Pi.map(t=>{const n=wi.has(t.domain);return e.jsxs(he.Fragment,{children:[e.jsxs(fe,{hover:!0,children:[e.jsx(I,{sx:{width:48,verticalAlign:"middle"},children:e.jsx(lt,{size:"small","aria-label":n?"Hide cited URLs":"Show cited URLs","aria-expanded":n,onClick:()=>Si(t.domain),children:e.jsx(dt,{sx:{transform:n?"rotate(180deg)":"rotate(0deg)",transition:i=>i.transitions.create("transform",{duration:i.transitions.duration.shorter})}})})}),e.jsx(I,{sx:{verticalAlign:"middle"},children:e.jsx(r,{variant:"body2",component:"span",children:t.domain})}),e.jsx(I,{align:"right",children:t.promptCount}),e.jsx(I,{align:"right",children:t.citationCount})]}),e.jsx(fe,{children:e.jsx(I,{sx:{py:0,borderBottom:n?void 0:"none"},colSpan:4,children:e.jsx(Ji,{in:n,timeout:"auto",unmountOnExit:!0,children:e.jsx(d,{sx:{py:1.5,pl:1,pr:1,bgcolor:"action.hover",borderRadius:1},children:t.citedUrls.length>0?e.jsxs(oe,{spacing:1,children:[e.jsx(r,{variant:"caption",color:"text.secondary",sx:{display:"block"},children:"Cited URLs from this domain"}),t.citedUrls.map((i,o)=>e.jsxs(d,{sx:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:1,flexWrap:"wrap"},children:[e.jsx(zt,{href:i.displayHref,target:"_blank",rel:"noopener noreferrer",variant:"body2",sx:{wordBreak:"break-all"},children:i.displayHref}),e.jsxs(r,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:["×",i.count]})]},`${t.domain}-${o}-${i.displayHref}`))]}):e.jsx(r,{variant:"body2",color:"text.secondary",children:"No individual URLs recorded for this domain (citations may be domain-only)."})})})})})]},t.domain)})})]})}):e.jsx(r,{variant:"body2",color:"text.secondary",children:"No citation sources found yet."})]})]}),Z===E.actions&&e.jsx(Ge,{title:"Action list",children:e.jsxs(Be,{sx:{p:3,mb:0},children:[e.jsxs(r,{variant:"body2",color:"text.secondary",sx:{mb:2},children:["Prompts that have an AI Overview but don’t cite you yet. Click ",e.jsx("strong",{children:"Create brief"})," to open the Content page and start generating a brief for that prompt."]}),zn.length===0?e.jsx(r,{variant:"body2",color:"text.secondary",children:"No uncited prompts with AI Overviews. Run AI Overview checks to find opportunities."}):e.jsx(ht,{sx:{maxWidth:{xs:"100%",sm:720,md:800},width:"100%"},children:e.jsxs(mt,{size:"small",sx:{tableLayout:"fixed",width:"100%"},children:[e.jsxs("colgroup",{children:[e.jsx("col",{}),e.jsx("col",{style:{width:120}}),e.jsx("col",{style:{width:132}})]}),e.jsx(ut,{children:e.jsxs(fe,{children:[e.jsx(I,{children:"Prompt"}),e.jsx(I,{align:"right",sx:{whiteSpace:"nowrap",pl:1},children:e.jsx(Ne,{title:"Number of citations (sources) in the AI Overview for this prompt",children:e.jsx("span",{children:"Citations"})})}),e.jsx(I,{align:"right",sx:{whiteSpace:"nowrap",pl:1},children:"Action"})]})}),e.jsx(pt,{children:zn.map(t=>e.jsxs(fe,{children:[e.jsx(I,{sx:{pr:2,verticalAlign:"top",wordBreak:"break-word",overflowWrap:"anywhere"},children:t.text}),e.jsx(I,{align:"right",sx:{whiteSpace:"nowrap",verticalAlign:"top",pl:1},children:t.citationCount??0}),e.jsx(I,{align:"right",sx:{verticalAlign:"top",pl:1},children:e.jsx(je,{size:"small",component:Xn,to:`/content-brief?promptId=${encodeURIComponent(t.promptId)}`,variant:"outlined",children:"Create brief"})})]},t.promptId))})]})})]})}),Z===E.recommendationsHistory&&e.jsx(Ge,{title:"Recommendations history",children:e.jsxs(Be,{sx:{p:3,mb:0},children:[e.jsxs(r,{variant:"body2",color:"text.secondary",sx:{mb:2},children:["Past AI recommendations are stored here when new ones are generated (e.g. from Overview or Settings refresh). Mark items as actioned when you have addressed them.",ve()&&ke?" Use the In portal column to control which rows appear for client users (or manage this in Settings → Recommendation history — portal visibility).":ve()?" To show an In portal column here, enable it in Settings → Recommendations Lab → Recommendation history — portal visibility.":" Your admin can hide individual rows from this list in Settings if needed."]}),Wt?e.jsxs(d,{display:"flex",alignItems:"center",gap:2,py:3,children:[e.jsx(ze,{size:24}),e.jsx(r,{variant:"body2",color:"text.secondary",children:"Loading recommendation history..."})]}):Ue.length===0?e.jsx(r,{variant:"body2",color:"text.secondary",children:"No recommendation history yet. Generate or refresh recommendations from the Overview tab or Settings to start building history."}):e.jsxs(e.Fragment,{children:[e.jsxs(d,{sx:{mb:2,display:"flex",flexWrap:"wrap",alignItems:"center",gap:2},children:[e.jsxs(Se,{size:"small",sx:{minWidth:220},children:[e.jsx(Ae,{id:"rec-history-actioned-filter",children:"Show rows"}),e.jsxs(Ie,{labelId:"rec-history-actioned-filter",label:"Show rows",value:Lt,onChange:t=>Bn(t.target.value),children:[e.jsx(M,{value:"all",children:"All"}),e.jsx(M,{value:"not_actioned",children:"Not actioned"}),e.jsx(M,{value:"actioned",children:"Actioned"})]})]}),e.jsxs(r,{variant:"caption",color:"text.secondary",children:["Showing ",rn.length," of ",Ue.length]})]}),rn.length===0?e.jsxs(r,{variant:"body2",color:"text.secondary",children:["No rows match this filter. Cho
4ose ",e.jsx("strong",{children:"All"})," or switch the filter to see other items."]}):e.jsx(ht,{sx:{width:"100%",overflowX:"auto"},children:e.jsxs(mt,{size:"small",sx:{width:"100%",minWidth:ve()&&ke?1080:980,tableLayout:"fixed","& .MuiTableCell-root":{px:2.5,py:1.5}},children:[e.jsx(ut,{children:e.jsxs(fe,{children:[e.jsx(I,{sx:{fontWeight:600,width:ve()&&ke?"12%":"14%",minWidth:152},children:"Date added"}),e.jsx(I,{sx:{fontWeight:600,width:ve()&&ke?"16%":"18%",minWidth:168},children:"Title"}),e.jsx(I,{sx:{fontWeight:600,width:ve()&&ke?"38%":"48%",minWidth:400},children:"Description"}),e.jsx(I,{sx:{fontWeight:600,width:ve()&&ke?"11%":"12%",minWidth:136,whiteSpace:"nowrap"},children:"Actioned on"}),ve()&&ke?e.jsx(I,{align:"center",sx:{fontWeight:600,width:"8%",minWidth:92},children:"In portal"}):null,e.jsx(I,{align:"center",sx:{fontWeight:600,width:ve()&&ke?"15%":"8%",minWidth:104,whiteSpace:"nowrap"},children:"Actioned"})]})}),e.jsx(pt,{children:rn.map(t=>e.jsxs(fe,{children:[e.jsx(I,{sx:{whiteSpace:"nowrap",verticalAlign:"top",fontSize:"0.8rem"},children:t.createdAt?new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}),e.jsx(I,{sx:{verticalAlign:"top",wordBreak:"break-word"},children:t.title}),e.jsx(I,{sx:{verticalAlign:"top",wordBreak:"break-word",overflowWrap:"anywhere"},children:e.jsx(r,{variant:"body2",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:8,WebkitBoxOrient:"vertical",lineHeight:1.5},children:t.description||"—"})}),e.jsx(I,{sx:{whiteSpace:"nowrap",verticalAlign:"top",fontSize:"0.8rem"},children:t.actioned&&t.actionedAt?new Date(t.actionedAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}),ve()&&ke?e.jsx(I,{align:"center",sx:{verticalAlign:"top"},children:e.jsx(ti,{size:"small",checked:!!t.shownInPortal,disabled:!!Li[t.id],onChange:(n,i)=>Ei(t.id,i),color:"secondary"})}):null,e.jsx(I,{align:"center",sx:{verticalAlign:"top"},children:e.jsx(ti,{size:"small",checked:!!t.actioned,disabled:!!Wi[t.id],onChange:(n,i)=>Ti(t.id,i),color:"primary"})})]},t.id))})]})})]})]})}),e.jsxs(Qi,{open:ki,onClose:()=>sn(!1),maxWidth:"sm",fullWidth:!0,children:[e.jsx(Xi,{children:"Change Tracking Domain"}),e.jsxs(Zi,{dividers:!0,children:[e.jsx(r,{variant:"body2",color:"text.secondary",paragraph:!0,children:"Changing the tracking domain will reload all prompts and metrics for the new domain."}),e.jsx(ei,{label:"Tracking Domain",fullWidth:!0,value:Je,onChange:t=>$i(t.target.value),placeholder:"e.g., frannet.com",helperText:"Enter the domain you want to track for citations",margin:"normal",autoFocus:!0}),Je!==V&&Je.trim()!==""&&e.jsxs(ye,{severity:"info",sx:{mt:2},children:["Current domain: ",e.jsx("strong",{children:V}),e.jsx("br",{}),"New domain: ",e.jsx("strong",{children:Je})]})]}),e.jsxs(es,{children:[e.jsx(je,{onClick:()=>sn(!1),children:"Cancel"}),e.jsx(je,{onClick:()=>{sn(!1)},variant:"contained",color:"primary",disabled:Je.trim()===""||Je===V,children:"Confirm Change"})]})]}),!1,De&&Z===E.competitors&&Xt&&(s==null?void 0:s.competitor_metrics)&&Object.keys(s.competitor_metrics).length>0&&e.jsx(le,{sx:{mb:0},children:e.jsxs(de,{children:[e.jsxs(d,{display:"flex",alignItems:"center",gap:1,mb:2,children:[e.jsx(Gt,{color:"primary"}),e.jsx(Ne,{title:e.jsxs(d,{children:[e.jsx(r,{variant:"body2",fontWeight:"bold",gutterBottom:!0,children:"Competitor Citation Comparison"}),e.jsxs(r,{variant:"body2",paragraph:!0,children:["This shows how often your brand and competitors are cited in Google AI Overviews ",e.jsx("strong",{children:"for the exact same search queries"})," you are tracking. Low numbers for a big national brand usually mean they were not cited on ",e.jsx("em",{children:"your"})," prompts yet—not that they are weak competitors. Use root domains (e.g. indeed.com), add category prompts, and re-run AI checks after saving competitors."]}),e.jsx(r,{variant:"body2",component:"div",gutterBottom:!0,children:e.jsx("strong",{children:"How it works:"})}),e.jsxs(r,{variant:"body2",component:"ul",sx:{mt:.5,mb:1,pl:2},children:[e.jsx("li",{children:'We search each of your tracked prompts (e.g., "franchise opportunities")'}),e.jsx("li",{children:"We check which brands appear as citations in that AI Overview"}),e.jsxs("li",{children:["We compare your citations vs. competitors' citations from the ",e.jsx("strong",{children:"same search results"})]})]}),e.jsx(r,{variant:"body2",component:"div",gutterBottom:!0,children:e.jsx("strong",{children:"What the metrics mean:"})}),e.jsxs(r,{variant:"body2",component:"ul",sx:{mt:.5,mb:0,pl:2},children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Total Citations:"})," How many times this brand appears as a source in AI Overviews"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Prompts Cited:"})," How many of your tracked prompts resulted in this brand being cited"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Coverage:"})," Percentage of AI Overviews where this brand was cited"]})]}),e.jsxs(r,{variant:"body2",sx:{mt:1},children:[e.jsx("strong",{children:"Note:"})," All brands are checked using the same prompts, so this is a fair, apples-to-apples comparison."]})]}
4),children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(d,{component:"span",sx:{display:"inline-flex",minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center",m:-1,p:1},children:e.jsx(lt,{size:"small",children:e.jsx(Fe,{fontSize:"small",color:"action"})})})})})})})})]}),e.jsx(d,{sx:{mb:2,maxWidth:220},children:e.jsxs(Se,{fullWidth:!0,size:"small",children:[e.jsx(Ae,{children:"Branding"}),e.jsxs(Ie,{label:"Branding",value:Pt,onChange:t=>yi(t.target.value),children:[e.jsx(M,{value:"all",children:"All"}),e.jsx(M,{value:"branded",children:"Branded"}),e.jsx(M,{value:"unbranded",children:"Unbranded"})]})]})}),e.jsx(He,{sx:{mb:2}}),$==="main"&&e.jsxs(ye,{severity:"info",sx:{mb:2},children:[e.jsxs(r,{variant:"body2",children:[e.jsx("strong",{children:"How this works:"})," We run the exact same prompts for your brand and competitors, checking who appears as citations in Google's AI Overviews. This gives you an apples-to-apples comparison."]}),s.competitor_metrics&&Object.values(s.competitor_metrics).every(t=>t.total_citations===0)&&e.jsxs(r,{variant:"body2",sx:{mt:1,fontWeight:600},children:["⚠️ Note: Competitor data shows 0 citations. This likely means:",e.jsxs("ul",{style:{marginTop:"8px",marginBottom:"8px",paddingLeft:"20px"},children:[e.jsx("li",{children:"Data was collected before competitors were configured, OR"}),e.jsx("li",{children:"Competitors genuinely weren't cited in those AI Overviews"})]}),'Click "Re-run AI Checks" in AEO Settings to collect fresh competitor data.']})]}),$!=="main"&&e.jsx(ye,{severity:"info",sx:{mb:2},children:e.jsxs(r,{variant:"body2",children:[e.jsx("strong",{children:"Viewing competitor data:"})," You're currently viewing metrics for ",e.jsx("strong",{children:$}),". Use the comparison toggle to see how this competitor compares to your main brand and other competitors."]})}),e.jsxs(J,{container:!0,spacing:3,children:[e.jsx(J,{item:!0,xs:12,md:3,children:e.jsxs(Be,{sx:{p:2,bgcolor:"grey.50",border:"2px solid",borderColor:"primary.main"},children:[e.jsxs(r,{variant:"subtitle2",fontWeight:600,gutterBottom:!0,color:"primary.main",children:[$==="main"?"Your Brand":"Selected Brand"," (",$==="main"?V:$,")"]}),e.jsx(r,{variant:"h4",color:"primary",children:st.selectedBrandMetrics.totalCitations||0}),e.jsx(r,{variant:"caption",color:"text.secondary",children:"Total Citations in AI Overviews"}),e.jsx(He,{sx:{my:1.5}}),e.jsxs(r,{variant:"body2",color:"text.secondary",children:[(st.selectedBrandMetrics.citedPrompts||0)===1?"1 prompt":`${st.selectedBrandMetrics.citedPrompts||0} prompts`," where you were cited"]}),e.jsxs(r,{variant:"body2",color:"text.secondary",children:[st.selectedBrandMetrics.coveragePercentage.toFixed(1),"% of AI Overviews cite you"]})]})}),Object.entries(st.competitorMetrics).map(([t,n])=>e.jsx(J,{item:!0,xs:12,md:3,children:e.jsxs(Be,{sx:{p:2,bgcolor:"grey.50",border:"1px solid",borderColor:"divider"},children:[e.jsxs(r,{variant:"subtitle2",fontWeight:600,gutterBottom:!0,children:["Competitor: ",t]}),e.jsx(r,{variant:"h4",color:n.total_citations>(s.clientCitations||0)?"error.main":n.total_citations===0?"text.secondary":"text.primary",children:n.total_citations}),e.jsx(r,{variant:"caption",color:"text.secondary",children:"Total Citations in AI Overviews"}),e.jsx(He,{sx:{my:1.5}}),e.jsxs(r,{variant:"body2",color:"text.secondary",children:[n.cited_prompts===1?"1 prompt":`${n.cited_prompts} prompts`," where ",t," was cited"]}),e.jsxs(r,{variant:"body2",color:"text.secondary",children:[n.coverage_percentage.toFixed(1),"% of AI Overviews cite them"]}),n.total_citations===0&&e.jsx(q,{label:"Not cited in tracked prompts",size:"small",color:"success",sx:{mt:1}}),n.total_citations>0&&n.total_citations>(s.clientCitations||0)&&e.jsx(q,{label:`+${n.total_citations-(s.clientCitations||0)} more citations than you`,size:"small",color:"error",sx:{mt:1}}),n.total_citations>0&&n.total_citations<(s.clientCitations||0)&&e.jsx(q,{label:`You have ${(s.clientCitations||0)-n.total_citations} more citations`,size:"small",color:"success",sx:{mt:1}})]})},t))]})]})}),Te&&Z===E.history&&e.jsx(Ge,{title:"Historical Trends",children:e.jsx(d,{sx:{mb:0,mt:1},children:e.jsx(ds,{})})})]})},Hs=()=>e.jsx(ls,{children:e.jsx(mi,{hideHeader:!0,children:e.jsx(Is,{})})});export{Is as GenerativeSEOReal,Hs as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.