1import{av as e,s as t,a,j as s,k as r,B as n,as as i,at as l,aw as o,Z as c,V as d}from"./index-DlHBLH5d.js";import{d as m,r as u}from"./i18n-BJnwxXTQ.js";import{S as h,a as x,b as p,c as y,d as f}from"./select-BEUVItE4.js";import{S as g}from"./skeleton-5nx0dtBQ.js";import{C as v}from"./chart-column-CZ6Gh0u-.js";import{T as j}from"./triangle-alert-BxkCZDXV.js";import{D as b}from"./download-QX5DKn5b.js";import{T as N}from"./trending-up-CFIBwK6o.js";import{i as w,D as S,f as k,L as A,a as E,C,A as O,b as P,c as D,d as T,h as I,e as _,G as L,g as R,j as F,u as U,E as $,k as z,X as B,Y as M,l as H,B as K,R as V,m as W,T as Y}from"./generateCategoricalChart-BLL0ZMv0.js";import{C as G}from"./clock-DuomGwjK.js";import{S as J}from"./server-CKdGukm4.js";import"./index-jVOyRz7F.js";import"./chevron-up-Dr9OhOPO.js";var q=["type","layout","connectNulls","ref"],X=["key"];function Z(e){return(Z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Q(e,t){if(null==e)return{};var a,s,r=function(e,t){if(null==e)return{};var a={};for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)){if(t.indexOf(s)>=0)continue;a[s]=e[s]}return a}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(s=0;s<n.length;s++)a=n[s],t.indexOf(a)>=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(r[a]=e[a])}return r}function ee(){return ee=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(e[s]=a[s])}return e},ee.apply(this,arguments)}function te(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),a.push.apply(a,s)}return a}function ae(e){for(var t=1;t<arguments.length;t++){var a=null!=arguments[t]?arguments[t]:{};t%2?te(Object(a),!0).forEach(function(t){de(e,t,a[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(a)):te(Object(a)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(a,t))})}return e}function se(e){return function(e){if(Array.isArray(e))return re(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return re(e,t);var a=Object.prototype.toString.call(e).slice(8,-1);"Object"===a&&e.constructor&&(a=e.constructor.name);if("Map"===a||"Set"===a)return Array.from(e);if("Arguments"===a||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a))return re(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function re(e,t){(null==t||t>e.length)&&(t=e.length);for(var a=0,s=new Array(t);a<t;a++)s[a]=e[a];return s}function ne(e,t){for(var a=0;a<t.length;a++){var s=t[a];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,me(s.key),s)}}function ie(e,t,a){return t=oe(t),function(e,t){if(t&&("object"===Z(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,le()?Reflect.construct(t,a||[],oe(e).constructor):t.apply(e,a))}function le(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(le=function(){return!!e})()}function oe(e){return(oe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function ce(e,t){return(ce=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function de(e,t,a){return(t=me(t))in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function me(e){var t=function(e,t){if("object"!=Z(e)||!e)return e;var a=e[Symbol.toPrimitive];if(void 0!==a){var s=a.call(e,t||"default");if("object"!=Z(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Z(t)?t:t+""}var ue=function(){function t(){var e;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);for(var a=arguments.length,s=new Array(a),r=0;r<a;r++)s[r]=arguments[r];return de(e=ie(this,t,[].concat(s)),"state",{isAnimationFinished:!0,totalLength:0}),de(e,"generateSimpleStrokeDasharray",function(e,t){return"".concat(t,"px ").concat(e-t,"px")}),de(e,"getStrokeDasharray",function(a,s,r){var n=r.reduce(function(e,t){return e+t});if(!n)return e.generateSimpleStrokeDasharray(s,a);for(var i=Math.floor(a/n),l=a%n,o=s-a,c=[],d=0,m=0;d<r.length;m+=r[d],++d)if(m+r[d]>l){c=[].concat(se(r.slice(0,d)),[l-m]);break}var u=c.length%2==0?[0,o]:[o];return[].concat(se(t.repeat(r,i)),se(c),u).map(function(e){return"".concat(e,"px")}).join(", ")}),de(e,"id",U("recharts-line-")),de(e,"pathRef",function(t){e.mainCurve=t}),de(e,"handleAnimationEnd",function(){e.setState({isAnimationFinished:!0}),e.props.onAnimationEnd&&e.props.onAnimationEnd()}),de(e,"handleAnimationStart",function(){e.setState({isAnimationFinished:!1}),e.props.onAnimationStart&&e.props.onAnimationStart()}),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ce(e,t)}(t,u.PureComponent),a=t,r=[{key:"getDerivedStateFromProps",value:function(e,t){return e.animationId!==t.prevAnimationId?{prevAnimationId:e.animationId,curPoints:e.points,prevPoints:t.curPoints}:e.points!==t.curPoints?{curPoints:e.points}:null}},{key:"repeat",value:function(e,t){for(var a=e.length%2!=0?[].concat(se(e),[0]):e,s=[],r=0;r<t;++r)s=[].concat(se(s),se(a));return s}},{key:"renderDotItem",value:function(t,a){var s;if(m.isValidElement(t))s=m.cloneElement(t,a);else if(w(t))s=t(a);else{var r=a.key,n=Q(a,X),i=e("recharts-line-dot","boolean"!=typeof t?t.className:"");s=m.createElement(S,ee({key:r},n,{className:i}))}return s}}],(s=[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var e=this.getTotalLength();this.setState({totalLength:e})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var e=this.getTotalLength();e!==this.state.totalLength&&this.setState({totalLength:e})}}},{key:"getTotalLength",value:function(){var e=this.mainCurve;try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch(t){return 0}}},{key:"renderErrorBar",value:function(e,t){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var a=this.props,s=a.points,r=a.xAxis,n=a.yAxis,i=a.layout,l=a.children,o=k(l,$);if(!o)return null;var c=function(e,t){return{x:e.x,y:e.y,value:e.value,errorVal:R(e.payload,t)}},d={clipPath:e?"url(#clipPath-".concat(t,")"):null};return m.createElement(A,d,o.map(function(e){return m.cloneElement(e,{key:"bar-".concat(e.props.dataKey),data:s,xAxis:r,yAxis:n,layout:i,dataPointFormatter:c})}))}},{key:"renderDots",value:function(e,a,s){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;
1var r=this.props,n=r.dot,i=r.points,l=r.dataKey,o=E(this.props,!1),c=E(n,!0),d=i.map(function(e,a){var s=ae(ae(ae({key:"dot-".concat(a),r:3},o),c),{},{index:a,cx:e.x,cy:e.y,value:e.value,dataKey:l,payload:e.payload,points:i});return t.renderDotItem(n,s)}),u={clipPath:e?"url(#clipPath-".concat(a?"":"dots-").concat(s,")"):null};return m.createElement(A,ee({className:"recharts-line-dots",key:"dots"},u),d)}},{key:"renderCurveStatically",value:function(e,t,a,s){var r=this.props,n=r.type,i=r.layout,l=r.connectNulls;r.ref;var o=Q(r,q),c=ae(ae(ae({},E(o,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:t?"url(#clipPath-".concat(a,")"):null,points:e},s),{},{type:n,layout:i,connectNulls:l});return m.createElement(C,ee({},c,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(e,t){var a=this,s=this.props,r=s.points,n=s.strokeDasharray,i=s.isAnimationActive,l=s.animationBegin,o=s.animationDuration,c=s.animationEasing,d=s.animationId,u=s.animateNewValues,h=s.width,x=s.height,p=this.state,y=p.prevPoints,f=p.totalLength;return m.createElement(O,{begin:l,duration:o,isActive:i,easing:c,from:{t:0},to:{t:1},key:"line-".concat(d),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(s){var i=s.t;if(y){var l=y.length/r.length,o=r.map(function(e,t){var a=Math.floor(t*l);if(y[a]){var s=y[a],r=P(s.x,e.x),n=P(s.y,e.y);return ae(ae({},e),{},{x:r(i),y:n(i)})}if(u){var o=P(2*h,e.x),c=P(x/2,e.y);return ae(ae({},e),{},{x:o(i),y:c(i)})}return ae(ae({},e),{},{x:e.x,y:e.y})});return a.renderCurveStatically(o,e,t)}var c,d=P(0,f)(i);if(n){var m="".concat(n).split(/[,\s]+/gim).map(function(e){return parseFloat(e)});c=a.getStrokeDasharray(d,f,m)}else c=a.generateSimpleStrokeDasharray(f,d);return a.renderCurveStatically(r,e,t,{strokeDasharray:c})})}},{key:"renderCurve",value:function(e,t){var a=this.props,s=a.points,r=a.isA
1nimationActive,n=this.state,i=n.prevPoints,l=n.totalLength;return r&&s&&s.length&&(!i&&l>0||!D(i,s))?this.renderCurveWithAnimation(e,t):this.renderCurveStatically(s,e,t)}},{key:"render",value:function(){var t,a=this.props,s=a.hide,r=a.dot,n=a.points,i=a.className,l=a.xAxis,o=a.yAxis,c=a.top,d=a.left,u=a.width,h=a.height,x=a.isAnimationActive,p=a.id;if(s||!n||!n.length)return null;var y=this.state.isAnimationFinished,f=1===n.length,g=e("recharts-line",i),v=l&&l.allowDataOverflow,j=o&&o.allowDataOverflow,b=v||j,N=T(p)?this.id:p,w=null!==(t=E(r,!1))&&void 0!==t?t:{r:3,strokeWidth:2},S=w.r,k=void 0===S?3:S,C=w.strokeWidth,O=void 0===C?2:C,P=(I(r)?r:{}).clipDot,D=void 0===P||P,L=2*k+O;return m.createElement(A,{className:g},v||j?m.createElement("defs",null,m.createElement("clipPath",{id:"clipPath-".concat(N)},m.createElement("rect",{x:v?d:d-u/2,y:j?c:c-h/2,width:v?u:2*u,height:j?h:2*h})),!D&&m.createElement("clipPath",{id:"clipPath-dots-".concat(N)},m.createElement("rect",{x:d-L/2,y:c-L/2,width:u+L,height:h+L}))):null,!f&&this.renderCurve(b,N),this.renderErrorBar(b,N),(f||r)&&this.renderDots(b,D,N),(!x||y)&&_.renderCallByParent(this.props,n))}}])&&ne(a.prototype,s),r&&ne(a,r),Object.defineProperty(a,"prototype",{writable:!1}),a;var a,s,r}();de(ue,"displayName","Line"),de(ue,"defaultProps",{xAxisId:0,yAxisId:0,connectNulls:!1,activeDot:!0,dot:!0,legendType:"line",stroke:"#3182bd",strokeWidth:1,fill:"#fff",points:[],isAnimationActive:!L.isSsr,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",hide:!1,label:!1}),de(ue,"getComposedData",function(e){var t=e.props,a=e.xAxis,s=e.yAxis,r=e.xAxisTicks,n=e.yAxisTicks,i=e.dataKey,l=e.bandSize,o=e.displayedData,c=e.offset,d=t.layout;return ae({points:o.map(function(e,t){var o=R(e,i);return"horizontal"===d?{x:F({axis:a,ticks:r,bandSize:l,entry:e,index:t}),y:T(o)?null:s.scale(o),value:o,payload:e}:{x:T(o)?null:a.scale(o),y:F({axis:s,ticks:n,bandSize:l,entry:e,index:t}),value:o,payload:e}}),layout:d},c)});var he=z({chartName:"LineChart",GraphicalChild:ue,axisComponents:[{axisType:"xAxis",AxisComp:B},{axisType:"yAxis",AxisComp:M}],formatAxisMap:H}),xe=z({chartName:"BarChart",GraphicalChild:K,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:B},{axisType:"yAxis",AxisComp:M}],formatAxisMap:H});function pe(){var e,d,m,w,S,k,A,E,C,O,P,D;const[T,I]=u.useState(null),[_,L]=u.useState(null),[R,F]=u.useState(null),[U,$]=u.useState(!1),[z,H]=u.useState(!1),[q,X]=u.useState(null),[Z,Q]=u.useState(!1),[ee,te]=u.useState(!1),[ae,se]=u.useState("overview"),[re,ne]=u.useState(10),[ie,le]=u.useState(10),[oe,ce]=u.useState(14),[de,me]=u.useState(1),[pe,ye]=u.useState("csv"),[,fe]=t(),{toast:ge}=a(),ve=u.useRef(!1),je=u.useCallback(()=>{localStorage.removeItem("analytics_token"),localStorage.removeItem("analytics_refresh_token"),localStorage.removeItem("analytics_token_expiry"),fe("/analytics-login")},[fe]),be=u.useCallback(e=>{ge({title:"Authentication required",description:e??"Your analytics session has expired. Please sign in again."}),je()},[ge,je]),Ne=u.useCallback(async()=>{const e=localStorage.getItem("analytics_refresh_token");if(!e)return!1;if(ve.current)return!0;ve.current=!0;try{const t=await fetch("/api/analytics/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!t.ok)return!1;const a=await t.json();if(!a.token)return!1;if(localStorage.setItem("analytics_token",a.token),a.refreshToken&&localStorage.setItem("analytics_refresh_token",a.refreshToken),"number"==typeof a.expiresIn){const e=Date.now()+1e3*a.expiresIn;localStorage.setItem("analytics_token_expiry",e.toString())}else localStorage.removeItem("analytics_token_expiry");return!0}catch(t){return console.error("Token refresh error:",t),!1}finally{ve.current=!1}},[]),we=u.useCallback(()=>{ne(e=>Math.min(e+10,200))},[]),Se=u.useCallback(()=>{le(e=>Math.min(e+10,200))},[]),ke=u.useCallback(()=>{ce(e=>Math.min(e+7,60))},[]),Ae=u.useCallback(()=>{Pe(de,pe)},[pe,de]),Ee=u.useCallback(async()=>{$(!0),X(null);try{const e=localStorage.getItem("analytics_token");if(!e)return void be("No authentication token found. Please sign in again.");const t=new URLSearchParams({toolLimit:re.toString(),resultLimit:ie.toString(),dailyLimit:oe.toString()}),a=await fetch(`/api/analytics/dashboard?${t.toString()}`,{headers:{Authorization:`Bearer ${e}`}});if(!a.ok){if(401===a.status)return void be();throw new Error(`Failed to fetch analytics: ${a.status}`)}const s=await a.json();I(s)}catch(e){X(e instanceof Error?e.message:"Failed to fetch analytics"),console.error("Analytics fetch error:",e),ge({title:"Failed to load anal
1ytics data",description:e instanceof Error?e.message:"An unexpected error occurred while loading analytics."})}finally{$(!1)}},[oe,be,ge,re,ie]),Ce=u.useCallback(async()=>{H(!0),X(null);try{const e=localStorage.getItem("analytics_token");if(!e)return void be("No authentication token found. Please sign in again.");const t=await fetch("/api/analytics/health/status",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){if(401===t.status)return void be();throw new Error(`Failed to fetch system health: ${t.status}`)}const a=await t.json();a.success&&a.data&&L(a.data)}catch(e){console.error("System health fetch error:",e),X(e.message||"Failed to fetch system health data"),ge({title:"Failed to load system health",description:(null==e?void 0:e.message)||"Unable to retrieve system health metrics."})}finally{H(!1)}},[be,ge]),Oe=u.useCallback(async(e=24)=>{try{const t=localStorage.getItem("analytics_token");if(!t)return void be("No authentication token found. Please sign in again.");const a=await fetch(`/api/analytics/errors/analysis/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!a.ok){if(401===a.status)return void be();throw new Error(`Failed to fetch error analytics: ${a.status}`)}const s=await a.json();s.success&&s.data&&F(s.data)}catch(t){console.error("Error analytics fetch error:",t),ge({title:"Failed to load error analytics",description:(null==t?void 0:t.message)||"Unable to retrieve error analytics data."})}},[be,ge]),Pe=async(e,t="csv")=>{Q(!0);try{const a=localStorage.getItem("analytics_token");if(!a)return void be("No authentication token found. Please sign in again.");const s=await fetch(`/api/analytics/export/${e}?format=${t}`,{headers:{Authorization:`Bearer ${a}`}});if(!s.ok){if(401===s.status)return void be();throw new Error(`Failed to export data: ${s.status}`)}const r=await s.blob(),n=window.URL.createObjectURL(r),i=document.createElement("a");i.href=n;const l=(new Date).toISOString().split("T")[0];i.download=`analytics-export-${e}months-${l}.${t}`,document.body.appendChild(i),i.click(),document.body.removeChild(i),window.URL.revokeObjectURL(n)}catch(a){console.error("Export error:",a),ge({title:"Export failed",description:a instanceof Error?a.message:"Unable to export analytics data at this time."})}finally{Q(!1)}},De=async()=>{try{const e=localStorage.getItem("analytics_token");if(e){const t=await fetch("/api/analytics/logout",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!t.ok&&401!==t.status)throw new Error(`Logout request failed with status ${t.status}`)}}catch(e){console.error("Logout error:",e),ge({title:"Logout failed",description:e instanceof Error?e.message:"An unexpected error occurred while logging out."})}finally{je()}};if(u.useEffect(()=>{const e=()=>{const e=localStorage.getItem("analytics_token");if(e)try{const t=localStorage.getItem("analytics_token_expiry");let a=null;if(t){const e=Number(t);Number.isNaN(e)||(a=e)}const s=JSON.parse(atob(e.split(".")[1]));if(!a&&s.exp&&(a=1e3*s.exp),!a)return;const r=a-Date.now();if(r<=0)return void Ne().then(e=>{e||be("Your session has expired. Please sign in again.")});if(r<=3e5)return void Ne().then(e=>{te(!e)});te(r<=18e5)}catch(t){console.error("Token parsing error:",t),be("Authentication token could not be validated. Please sign in again.")}};e();const t=setInterval(e,6e4);return()=>clearInterval(t)},[be,Ne]),u.useEffect(()=>{Ee(),"health"===ae&&(Ce(),Oe())},[ae,Ee,Ce,Oe]),u.useEffect(()=>{if("health"===ae){const e=setInterval(()=>{document.hidden||(Ce(),Oe())},3e4);return()=>clearInterval(e)}},[ae,Oe,Ce]),u.useEffect(()=>{if("overview"!==ae)return;const e=setInterval(()=>{document.hidden||Ee()},3e5);return()=>clearInterval(e)},[ae,Ee]),U)return s.jsxs("div",{className:"max-w-6xl mx-auto p-6 space-y-6",children:[s.jsx(g,{className:"h-10 w-1/3"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(g,{className:"h-40 w-full"}),s.jsx(g,{className:"h-40 w-full"})]}),s.jsx(g,{className:"h-64 w-full"})]});if(q)return s.jsx("div",{className:"max-w-6xl mx-auto p-6",children:s.jsx(r,{className:"p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-red-500 mb-4",children:"Error loading analytics"}),s.jsx("div",{className:"text-sm text-gray-600 mb-4",children:q}),s.jsx(n,{onClick:Ee,variant:"outline",children:"Retry"})]})})});if(!T)return s.jsx("div",{className:"max-w-6xl mx-auto p-6",children:s.jsx(r,{className:"p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-gray-500 mb-4",children:"No anal
1ytics data available"}),s.jsx(n,{onClick:Ee,variant:"outline",children:"Refresh"})]})})});return s.jsxs("div",{className:"max-w-6xl mx-auto p-6 space-y-6",children:[s.jsxs(r,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-3xl font-bold text-gray-900",children:"FaceAura AI Analytics"}),s.jsx("p",{className:"text-gray-600",children:"Comprehensive analytics dashboard for AI-powered beauty analysis"}),T.metadata&&s.jsxs("p",{className:"text-sm text-gray-500 mt-1",children:["Last updated ",new Date(T.metadata.generatedAt).toLocaleString(),T.metadata.dateRange.start&&T.metadata.dateRange.end&&s.jsxs("span",{children:[" ","⢠Data range: ",T.metadata.dateRange.start," â ",T.metadata.dateRange.end]})]})]}),s.jsx("div",{className:"flex items-center space-x-4",children:s.jsxs(n,{onClick:De,variant:"outline",className:"flex items-center space-x-2",children:[s.jsx(i,{className:"h-4 w-4"}),s.jsx("span",{children:"Logout"})]})})]}),s.jsxs("div",{className:"flex space-x-1 border-b border-gray-200",children:[s.jsx("button",{onClick:()=>se("overview"),className:"px-4 py-2 text-sm font-medium rounded-t-lg border-b-2 transition-colors "+("overview"===ae?"border-purple-500 text-purple-600 bg-purple-50":"border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50"),children:s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(v,{className:"h-4 w-4"}),s.jsx("span",{children:"Overview"})]})}),s.jsx("button",{onClick:()=>se("health"),className:"px-4 py-2 text-sm font-medium rounded-t-lg border-b-2 transition-colors "+("health"===ae?"border-purple-500 text-purple-600 bg-purple-50":"border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50"),children:s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(l,{className:"h-4 w-4"}),s.jsx("span",{children:"System Health"})]})}),s.jsx("button",{onClick:()=>se("errors"),className:"px-4 py-2 text-sm font-medium rounded-t-lg border-b-2 transition-colors "+("errors"===ae?"border-purple-500 text-purple-600 bg-purple-50":"border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50"),children:s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(j,{className:"h-4 w-4"}),s.jsx("span",{children:"Error Analysis"})]})})]})]}),"health"===ae&&(z&&!_?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600 mx-auto mb-4"}),s.jsx("p",{className:"text-gray-600",children:"Loading system health data..."})]})}):s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[s.jsx(r,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-gray-600",children:"CPU Usage"}),s.jsxs("p",{className:"text-2xl font-bold text-gray-900",children:[(null==(Ie=null==(Te=null==_?void 0:_.currentHealth)?void 0:Te.cpu_usage)?void 0:Ie.toFixed(1))||"--","%"]})]}),s.jsx(J,{className:"h-8 w-8 text-blue-600"})]})}),s.jsx(r,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-gray-600",children:"Memory Usage"}),s.jsxs("p",{className:"text-2xl font-bold text-gray-900",children:[(null==(Le=null==(_e=null==_?void 0:_.currentHealth)?void 0:_e.memory_usage)?void 0:Le.toFixed(1))||"--","%"]})]}),s.jsx(l,{className:"h-8 w-8 text-green-600"})]})}),s.jsx(r,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-gray-600",children:"Response Time"}),s.jsxs("p",{className:"text-2xl font-bold text-gray-900",children:[(null==(Fe=null==(Re=null==_?void 0:_.currentHealth)?void 0:Re.response_time_avg)?void 0:Fe.toFixed(0))||"--","ms"]})]}),s.jsx(c,{className:"h-8 w-8 text-yellow-600"})]})}),s.jsx(r,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-gray-600",children:"System Status"}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx("div",{className:"w-3 h-3 rounded-full "+("healthy"===(null==(Ue=null==_?void 0:_.currentHealth)?void 0:Ue.status)?"bg-green-500":"warning"===(null==($e=null==_?void 0:_.currentHealth)?void 0:$e.status)?"bg-yellow-500":"bg-red-500")}),s.jsx("p",{className:"text-lg font-semibold capitalize",children:(null==(ze=null==_?void 0:_.currentHealth)?void 0:ze.status)||"Unknown"})]})]}),s.jsx(l,{className:"h-8 w-8 text-purple-600"})]})})]}),(null==_?void 0:_.recentErrors)&&_.recentErrors.length>0&&s.jsxs(r,{className:"p-6",children:[s.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Recent Errors (Last Hour)"}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:_.recentErrors.map((e,t)=>s.jsxs("div",{className:"p-3 bg-red-50 rounded-lg border border-red-200",children:[s.jsx("p",{className:"text-sm font-medium text-red-800",children:e.severity}),s.jsxs("p",{className:"text-lg font-bold text-red-900",children:[e.count," errors"]})]},t))})]}),(null==_?void 0:_.recentSecurityEvents)&&_.recentSecurityEvents.length>0&&s.jsxs(r,{className:"p-6",children:[s.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Security Events (Last 24 Hours)"}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:_.recentSecurityEvents.map((e,t)=>s.jsxs("div",{className:"p-3 bg-orange-50 rounded-lg border border-orange-200",children:[s.jsx("p",{className:"text-sm font-medium text-orange-800",children:e.event_type}),s.jsxs("p",{className:"text-lg font-bold text-orange-900",children:[e.count," events"]})]},t))})]}),s.jsxs("div",{className:"text-center text-sm text-gray-500",children:["Data auto-refreshes every 30 seconds ⢠Last updated:"," ",new Date((null==(Be=null==_?void 0:_.currentHealth)?void 0:Be.timestamp)||(null==_?void 0:_.timestamp)||Date.now()).toLocaleTimeString()]})]})),"errors"===ae&&(R?s.jsxs("div",{className:"space-y-6",children:[s.jsxs(r,{className:"p-6",children:[s.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Errors by Type (Last 24 Hours)"}),R.errorsByType.length>0?s.jsx("div",{className:"space-y-3",children:R.errorsByType.map((e,t)=>s.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-gray-900",children:e.error_type}),s.jsxs("p",{className:"text-sm text-gray-600",children:["Last: ",new Date(e.latest_occurrence).toLocaleStr
1ing()]})]}),s.jsxs("div",{className:"text-right",children:[s.jsx("p",{className:"text-lg font-bold text-red-600",children:e.count}),s.jsx("p",{className:"text-sm text-gray-500",children:"occurrences"})]})]},t))}):s.jsx("p",{className:"text-gray-500",children:"No errors recorded in the last 24 hours"})]}),R.criticalErrors.length>0&&s.jsxs(r,{className:"p-6 border-red-200 bg-red-50",children:[s.jsx("h3",{className:"text-lg font-semibold mb-4 text-red-800",children:"Critical Errors"}),s.jsx("div",{className:"space-y-3",children:R.criticalErrors.map((e,t)=>s.jsx("div",{className:"p-3 bg-white rounded-lg border border-red-200",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-red-900",children:e.error_type}),s.jsx("p",{className:"text-sm text-red-700 mt-1",children:e.error_message}),e.endpoint&&s.jsxs("p",{className:"text-xs text-red-600 mt-2",children:["Endpoint: ",e.endpoint]})]}),s.jsx("p",{className:"text-xs text-red-600",children:new Date(e.timestamp).toLocaleString()})]})},t))})]})]}):s.jsxs("div",{className:"text-center py-12",children:[s.jsx(j,{className:"h-12 w-12 text-gray-400 mx-auto mb-4"}),s.jsx("p",{className:"text-gray-600",children:"No error analytics data available"})]})),"overview"===ae&&s.jsxs("div",{className:"space-y-6",children:[ee&&s.jsx(r,{className:"p-4 border-orange-200 bg-orange-50",children:s.jsxs("div",{className:"flex items-center gap-3 text-orange-800",children:[s.jsx(j,{className:"w-5 h-5"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:"Session expiring soon"}),s.jsx("div",{className:"text-sm",children:"Your session will expire in less than 30 minutes. Save your work or refresh your session."})]}),s.jsx(n,{size:"sm",variant:"outline",onClick:()=>te(!1),className:"ml-auto",children:"Dismiss"})]})}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h1",{className:"text-3xl font-bold flex items-center gap-3",children:[s.jsx(v,{className:"w-8 h-8 text-purple-600"}),"Analytics Dashboard"]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(n,{onClick:Ee,variant:"outline",children:"Refresh Data"}),s.jsx(n,{onClick:async()=>{const e=(new Date).toISOString().split("T")[0];try{const t=localStorage.getItem("analytics_token");if(!t)return void be("No authentication token found. Please sign in again.");const a=await fetch("/api/analytics/daily-summary",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({date:e})});if(a.ok){const e=await a.json();ge({title:"Daily summary generated",description:e.message||"Daily summary created successfully."}),Ee()}else{if(401===a.status)return void be();const e=await a.json();ge({title:"Failed to generate daily summary",description:e.message||"An unexpected error occurred while generating the summary."})}}catch(t){console.error("Daily summary error:",t),ge({title:"Failed to generate daily summary",description:t instanceof Error?t.message:"An unexpected error occurred while generating the summary."})}},variant:"default",children:"Generate Daily Summary"}),s.jsxs(n,{onClick:De,variant:"destructive",size:"sm",children:[s.jsx(i,{className:"w-4 h-4 mr-2"}),"Logout"]})]})]}),s.jsxs(r,{className:"p-6",children:[s.jsx("div",{className:"flex items-center justify-between mb-4",children:s.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[s.jsx(b,{className:"w-5 h-5 text-blue-600"}),"Export Analytics Data"]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-medium",children:"Time Period:"}),s.jsxs(h,{value:de.toString(),onValueChange:e=>me(Number(e)),children:[s.jsx(x,{className:"w-32",children:s.jsx(p,{placeholder:"Select range"})}),s.jsxs(y,{children:[s.jsx(f,{value:"1",children:"1 Month"}),s.jsx(f,{value:"2",children:"2 Months"}),s.jsx(f,{value:"6",children:"6 Months"}),s.jsx(f,{value:"12",children:"1 Year"}),s.jsx(f,{value:"24",children:"2 Years"}),s.jsx(f,{value:"0",children:"All Time"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-medium",children:"Format:"}),s.jsxs(h,{value:pe,onValueChange:e=>ye(e),children:[s.jsx(x,{className:"w-28",children:s.jsx(p,{placeholder:"Format"})}),s.jsxs(y,{children:[s.jsx(f,{value:"csv",children:"CSV"}),s.jsx(f,{value:"json",children:"JSON"})]})]})]}),s.jsx(n,{onClick:Ae,variant:"default",disabled:Z,children:Z?"Preparing...":"Download"})]})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[s.jsxs(r,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx(N,{className:"w-5 h-5 text-green-600"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Tool Usage"})]}),T.toolUsage&&T.toolUsage.length>0&&s.jsx("div",{className:"h-48 mb-4",children:s.jsx(V,{width:"100%",height:"100%",children:s.jsxs(xe,{data:T.toolUsage,children:[s.jsx(W,{strokeDasharray:"3 3"}),s.jsx(B,{dataKey:"toolName",hide:!0,tick:{fontSize:10}}),s.jsx(M,{allowDecimals:!1}),s.jsx(Y,{}),s.jsx(K,{dataKey:"totalUses",fill:"#6366f1",radius:[4,4,0,0]})]})})}),s.jsxs("div",{className:"space-y-3",children:[null==(e=T.toolUsage)?void 0:e.map((e,t)=>s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:e.toolName}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"px-2 py-1 text-xs bg-gray-100 border rounded",children:[e.totalUses," uses"]}),s.jsxs("span",{className:"px-2 py-1 text-xs rounded "+(e.successRate>90?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"),children:[e.successRate.toFixed(1),"%"]})]})]},t)),T.toolUsage&&0===T.toolUsage.length&&s.jsx("div",{className:"text-sm text-gray-500",children:"No tool usage data available."})]}),(null==(w=null==(m=null==(d=T.metadata)?void 0:d.pagination)?void 0:m.toolUsage)?void 0:w.hasMore)&&s.jsx("div",{className:"mt-4",children:s.jsx(n,{variant:"ghost",size:"sm",onClick:we,children:"Load more tools"})})]}),s.jsxs(r,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx(o,{className:"w-5 h-5 text-blue-600"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Top Results"})]}),s.jsxs("div",{className:"space-y-3",children:[null==(S=T.topResults)?void 0:S.map((e,t)=>s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:e.result}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs text-gray-500",children:e.toolName}),s.jsx("span",{className:"px-2 py-1 text-xs bg-gray-100 border rounded",children:e.count}),"number"==typeof e.averageConfidence&&s.jsxs("span",{className:"px-2 py-1 text-xs bg-purple-50 text-purple-700 border border-purple-100 rounded",children:[e.averageConfidence.toFixed(1),"%"]})]})]},t)),T.topResults&&0===T.topResults.length&&s.jsx("div",{className:"text-sm text-gray-500",children:"No result analytics available."})]}),(null==(E=null==(A=null==(k=T.metadata)?void 0:k.pagination)?void 0:A.topResults)?void 0:E.hasMore)&&s.jsx("div",{className:"mt-4",children:s.jsx(n,{variant:"ghost",size:"sm",onClick:Se,children:"Load more results"})})]}),s.jsxs(r,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx(G,{className:"w-5 h-5 text-orange-600"}),s.jsx("h3",{className:"text-lg font-semibold",children:"Performance"})]}),s.jsx("div",{className:"space-y-3",children:null==(C=T.toolUsage)?void 0:C.slice(0,5).map((e,t)=>s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:e.toolName}),s.jsxs("span",{className:"px-2 py-1 text-xs bg-gray-100 border rounded",children:[e.avgProcessingTime.toFixed(0),"ms avg"]})]},t))})]})]}),T.demographics&&T.demographics.length>0&&s.jsxs(r,{className:"p-6",children:[s.jsx("h3",{className:"text-lg font-semibold mb-4",children:"User Demographics"}),s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:T.demographics.map((e,t)=>s.jsxs("div",{className:"text-center p-4 bg-gray-50 rounded-lg",children:[s.jsx("div",{className:"text-2xl font-bold text-purple-600",children:e.count}),s.jsx("div",{className:"text-sm text-gray-600",children:e.ageRange})]},t))})]}),T.dailyStats&&T.dailyStats.length>0&&s.jsxs(r,{className:"p-6",children:[s.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Recent Daily Activity"}),s.jsx("div",{className:"h-56 mb-6",children:s.jsx(V,{width:"100%",height:"100%",children:s.jsxs(he,{data:T.dailyStats,children:[s.jsx(W,{strokeDasharray:"3 3"}),s.jsx(B,{dataKey:"date",tick:{fontSize:10}}),s.jsx(M,{allowDecimals:!1}),s.jsx(Y,{}),s.jsx(ue,{type:"monotone",dataKey:"totalScans",stroke:"#6366f1",strokeWidth:2,dot:!1}),s.jsx(ue,{type:"monotone",dataKey:"successfulScans",stroke:"#10b981",strokeWidth:2,dot:!1})]})})}),s.jsx("div",{className:"space-y-3",children:T.dailyStats.map((e,t)=>s.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg",children:[s.jsx("span",{className:"font-medium",children:e.date}),s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("span",{className:"text-sm",children:["Total: ",e.totalScans]}),s.jsxs("span",{className:"text-sm",children:["Successful: ",e.successfulScans]}),s.jsxs("span",{className:"text-sm",children:["Avg: ",e.averageProcessingTime,"ms"]}),s.jsxs("span",{className:"px-2 py-1 text-xs bg-gray-100 border rounded",children:[Number.isFinite(e.successRate)?e.successRate.toFixed(1):"0.0","%"]})]})]},t))}),(null==(D=null==(P=null==(O=T.metadata)?void 0:O.pagination)?void 0:P.dailyStats)?void 0:D.hasMore)&&s.jsx("div",{className:"mt-4",children:s.jsx(n,{variant:"ghost",size:"sm",onClick:ke,children:"Load more days"})})]})]})]});var Te,Ie,_e,Le,Re,Fe,Ue,$e,ze,Be}function ye(){const[,e]=t(),[a,r]=u.useState(!1),[n,i]=u.useState(!0),l=()=>{localStorage.removeItem("analytics_token"),localStorage.removeItem("analytics_refresh_token"),localStorage.removeItem("analytics_token_expiry")};u.useEffect(()=>{o()},[]);const o=async()=>{const t=localStorage.getItem("analytics_token");if(!t)return l(),void e("/analytics-login");try{(await fetch("/api/analytics/verify",{headers:{Authorization:`Bearer ${t}`}})).ok?r(!0):(l(),e("/analytics-login"))}catch(a){console.error("Auth verification failed:",a),l(),e("/analytics-login")}finally{i(!1)}};return n?s.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:s.jsxs("div",{className:"text-center",children:[s.jsx(d,{className:"h-8 w-8 animate-spin text-purple-600 mx-auto mb-4"}),s.jsx("p",{className:"text-gray-600",children:"Verifying access..."})]})}):a?s.jsx(pe,{}):null}export{ye 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.