import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useNavigate, useOutletContext } from 'react-router-dom';
import {
  Row, Col, Card, Statistic, Typography, Tag, Badge, Button,
  Progress, Space, Tooltip, Spin, Grid, Flex, Segmented,
} from 'antd';
import {
  TeamOutlined,
  SendOutlined,
  EnvironmentOutlined,
  MailOutlined,
  VideoCameraOutlined,
  ScheduleOutlined,
  ReloadOutlined,
  PlusOutlined,
  UploadOutlined,
  FileTextOutlined,
  ScissorOutlined,
  CompassOutlined,
  RocketOutlined,
  CloudServerOutlined,
  DatabaseOutlined,
  BranchesOutlined,
  QrcodeOutlined,
  BarChartOutlined,
  GlobalOutlined,
  CodeOutlined,
  BookOutlined,
  DesktopOutlined,
  HddOutlined,
  DashboardOutlined,
  ContainerOutlined,
  ApiOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  MinusCircleFilled,
  HomeOutlined,
  LockOutlined,
  MessageOutlined,
  CalendarOutlined,
  LineChartOutlined,
} from '@ant-design/icons';
import {
  BarChart, Bar, XAxis, YAxis, Tooltip as RechartsTooltip,
  ResponsiveContainer, Cell,
} from 'recharts';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import { hasAnyRole } from '@/utils/roles';
import SystemGauges from '@/components/dashboard/SystemGauges';
import MiniDonutChart from '@/components/dashboard/MiniDonutChart';
import RequestTrafficChart from '@/components/dashboard/RequestTrafficChart';
import LatencyBandsChart from '@/components/dashboard/LatencyBandsChart';
import ContainerPopover from '@/components/dashboard/ContainerPopover';
import ContainerMemoryChart from '@/components/dashboard/ContainerMemoryChart';
import ActivityFeedCard from '@/components/dashboard/ActivityFeedCard';
import { PageTour } from '@/components/tour/PageTour';
import TodayEventsCard from '@/components/dashboard/TodayEventsCard';
import ChatNotifierCard from '@/components/dashboard/ChatNotifierCard';
import TopVideosCard from '@/components/dashboard/TopVideosCard';
import RecentCommentsCard from '@/components/dashboard/RecentCommentsCard';
import DocsAnalyticsCard from '@/components/dashboard/DocsAnalyticsCard';
import UpcomingShiftsCard from '@/components/dashboard/UpcomingShiftsCard';
import MyActionItemsCard from '@/components/dashboard/MyActionItemsCard';
import CampaignEffectivenessCard from '@/components/dashboard/CampaignEffectivenessCard';
import RecentSignupsCard from '@/components/dashboard/RecentSignupsCard';
import NewsletterStatsCard from '@/components/dashboard/NewsletterStatsCard';
import DonationSummaryCard from '@/components/dashboard/DonationSummaryCard';
import SystemAlertsCard from '@/components/dashboard/SystemAlertsCard';
import GiteaActivityCard from '@/components/dashboard/GiteaActivityCard';
import VaultwardenAdoptionCard from '@/components/dashboard/VaultwardenAdoptionCard';
import UpcomingMeetingsCard from '@/components/dashboard/UpcomingMeetingsCard';
import CutCampaignAnalyticsCard from '@/components/canvass/CutCampaignAnalyticsCard';
import { buildServiceUrl } from '@/lib/service-url';
import type {
  DashboardSummary, QueueStats, ServicesStatus, ServicesConfig,
  SystemInfo, ContainerInfo, WeatherData, ApiMetrics,
  TimeSeriesResult, ContainerResource, ContainerResourcesResponse,
  ConnectivityStatus,
  AppOutletContext,
} from '@/types/api';

const { Text } = Typography;

// --- Pulse animation CSS (injected once) ---
const PULSE_STYLE_ID = 'dashboard-pulse-css';
if (typeof document !== 'undefined' && !document.getElementById(PULSE_STYLE_ID)) {
  const style = document.createElement('style');
  style.id = PULSE_STYLE_ID;
  style.textContent = `
    @keyframes dashboard-pulse {
      0% { box-shadow: 0 0 0 0 rgba(82,196,26,0.5); }
      70% { box-shadow: 0 0 0 6px rgba(82,196,26,0); }
      100% { box-shadow: 0 0 0 0 rgba(82,196,26,0); }
    }
    .svc-badge-online .ant-badge-status-dot {
      animation: dashboard-pulse 2s infinite;
    }
    .db-mi { break-inside: avoid; margin-bottom: 16px; }
  `;
  document.head.appendChild(style);
}

const ROLE_COLORS: Record<string, string> = {
  SUPER_ADMIN: 'red',
  INFLUENCE_ADMIN: 'blue',
  MAP_ADMIN: 'green',
  USER: 'default',
  TEMP: 'orange',
};

const ROLE_LABELS: Record<string, string> = {
  SUPER_ADMIN: 'Super Admin',
  INFLUENCE_ADMIN: 'Influence',
  MAP_ADMIN: 'Map',
  USER: 'User',
  TEMP: 'Temp',
};

interface HealthStatus {
  status: string;
  checks: { database: string; redis: string };
}

function formatUptime(seconds: number): string {
  const d = Math.floor(seconds / 86400);
  const h = Math.floor((seconds % 86400) / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}

function getWeatherIcon(code: number, isDay: boolean): string {
  if (code === 0) return isDay ? '\u2600\uFE0F' : '\uD83C\uDF19';      // sun / moon
  if (code <= 2) return isDay ? '\u26C5' : '\uD83C\uDF19';              // partly cloudy / moon
  if (code === 3) return '\u2601\uFE0F';                                 // overcast
  if (code <= 48) return '\uD83C\uDF2B\uFE0F';                          // fog
  if (code <= 57) return '\uD83C\uDF27\uFE0F';                          // drizzle
  if (code <= 67) return '\uD83C\uDF27\uFE0F';                          // rain
  if (code <= 77) return '\u2744\uFE0F';                                 // snow
  if (code <= 82) return '\uD83C\uDF26\uFE0F';                          // rain showers
  if (code <= 86) return '\uD83C\uDF28\uFE0F';                          // snow showers
  return '\u26C8\uFE0F';                                                 // thunderstorm
}

/** Container tile background gradient based on status */
function containerTileBg(running: boolean, status: string): { bg: string; border: string } {
  if (running) return {
    bg: 'linear-gradient(135deg, rgba(82,196,26,0.08) 0%, rgba(82,196,26,0.02) 100%)',
    border: 'rgba(82,196,26,0.25)',
  };
  if (status === 'not_found') return {
    bg: 'linear-gradient(135deg, rgba(153,153,153,0.08) 0%, rgba(153,153,153,0.02) 100%)',
    border: 'rgba(153,153,153,0.25)',
  };
  return {
    bg: 'linear-gradient(135deg, rgba(255,77,79,0.10) 0%, rgba(255,77,79,0.03) 100%)',
    border: 'rgba(255,77,79,0.3)',
  };
}

/** Status code color for donut and bar charts */
function statusColor(code: string): string {
  if (code.startsWith('2')) return '#52c41a';
  if (code.startsWith('3')) return '#1890ff';
  if (code.startsWith('4')) return '#faad14';
  return '#ff4d4f';
}

const TIME_SERIES_METRICS = 'request_rate_2xx,request_rate_4xx,request_rate_5xx,latency_p50,latency_p95,latency_p99,cpu_usage,memory_usage';

export default function DashboardPage() {
  const navigate = useNavigate();
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { user } = useAuthStore();
  const { settings } = useSettingsStore();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const isSuperAdmin = hasAnyRole(user, ['SUPER_ADMIN']);

  useEffect(() => {
    setPageHeader({ title: 'Dashboard' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  const [summary, setSummary] = useState<DashboardSummary | null>(null);
  const [queue, setQueue] = useState<QueueStats | null>(null);
  const [health, setHealth] = useState<HealthStatus | null>(null);
  const [services, setServices] = useState<ServicesStatus | null>(null);
  const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
  const [containers, setContainers] = useState<ContainerInfo[] | null>(null);
  const [weather, setWeather] = useState<WeatherData | null>(null);
  const [apiMetrics, setApiMetrics] = useState<ApiMetrics | null>(null);
  const [timeSeries, setTimeSeries] = useState<TimeSeriesResult | null>(null);
  const [containerResources, setContainerResources] = useState<ContainerResource[] | null>(null);
  const [connectivity, setConnectivity] = useState<ConnectivityStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);
  const [activeView, setActiveView] = useState<'dashboard' | 'homepage'>('dashboard');
  const [homepageUrl, setHomepageUrl] = useState<string | null>(null);
  const [grafanaUrl, setGrafanaUrl] = useState<string | null>(null);
  const [onboardingDismissed, setOnboardingDismissed] = useState(() =>
    localStorage.getItem('cml-onboarding-dismissed') === 'true'
  );
  const intervalRef = useRef<ReturnType<typeof setInterval>>(undefined);

  const fetchData = useCallback(async () => {
    const promises: Promise<void>[] = [
      api.get<DashboardSummary>('/dashboard/summary').then(({ data }) => setSummary(data)).catch(() => {}),
      api.get<QueueStats>('/email-queue/stats').then(({ data }) => setQueue(data)).catch(() => {}),
      api.get<HealthStatus>('/health').then(({ data }) => setHealth(data)).catch(() => {}),
      api.get<WeatherData>('/dashboard/weather').then(({ data }) => {
        if ('error' in data) setWeather(null);
        else setWeather(data);
      }).catch(() => {}),
    ];
    if (isSuperAdmin) {
      promises.push(
        api.get<ServicesStatus>('/services/status').then(({ data }) => setServices(data)).catch(() => {}),
        api.get<ServicesConfig>('/services/config').then(({ data }) => {
          setHomepageUrl(buildServiceUrl(data.homepageSubdomain, data.domain, data.homepagePort));
          setGrafanaUrl(buildServiceUrl(data.grafanaSubdomain, data.domain, data.grafanaPort));
        }).catch(() => {}),
        api.get<SystemInfo>('/dashboard/system').then(({ data }) => setSystemInfo(data)).catch(() => {}),
        api.get<ContainerInfo[]>('/dashboard/containers').then(({ data }) => setContainers(data)).catch(() => {}),
        api.get<ApiMetrics>('/dashboard/api-metrics').then(({ data }) => {
          if ('error' in data) setApiMetrics(null);
          else setApiMetrics(data);
        }).catch(() => {}),
        api.get<TimeSeriesResult>('/dashboard/time-series', {
          params: { metrics: TIME_SERIES_METRICS, range: '1h', step: '5m' },
        }).then(({ data }) => setTimeSeries(data)).catch(() => {}),
        api.get<ContainerResourcesResponse>('/dashboard/container-resources').then(({ data }) => {
          setContainerResources(data.containers || []);
        }).catch(() => {}),
        api.get<ConnectivityStatus>('/dashboard/connectivity').then(({ data }) => setConnectivity(data)).catch(() => {}),
      );
    }
    await Promise.allSettled(promises);
    setLastRefresh(new Date());
    setLoading(false);
  }, [isSuperAdmin]);

  useEffect(() => {
    fetchData();
    intervalRef.current = setInterval(fetchData, 60_000);
    return () => clearInterval(intervalRef.current);
  }, [fetchData]);

  const handleRefresh = () => {
    setLoading(true);
    fetchData();
  };

  const showInfluence = settings?.enableInfluence !== false;
  const showMap = settings?.enableMap !== false;
  const showMedia = settings?.enableMediaFeatures !== false;
  const showEvents = settings?.enableEvents !== false;
  const showChat = settings?.enableChat !== false;
  const showNewsletter = settings?.enableNewsletter !== false;
  const showPayments = settings?.enablePayments !== false;
  const showMeet = settings?.enableMeet !== false;

  const geocodePct = summary && summary.locations.total > 0
    ? Math.round((summary.locations.geocoded / summary.locations.total) * 100) : 0;

  // Build container resource map for popovers
  const containerResourceMap = useMemo(() => {
    const map = new Map<string, ContainerResource>();
    if (containerResources) {
      for (const cr of containerResources) map.set(cr.name, cr);
    }
    return map;
  }, [containerResources]);

  // Campaign status donut data
  const campaignDonutData = useMemo(() => {
    if (!summary) return [];
    return [
      { name: 'Active', value: summary.campaigns.active, color: '#52c41a' },
      { name: 'Draft', value: summary.campaigns.draft, color: '#1890ff' },
      { name: 'Paused', value: summary.campaigns.paused, color: '#faad14' },
      { name: 'Archived', value: summary.campaigns.archived, color: '#999' },
    ];
  }, [summary]);

  // Status code donut data
  const statusDonutData = useMemo(() => {
    if (!apiMetrics?.statusBreakdown?.length) return [];
    return apiMetrics.statusBreakdown.map(s => ({
      name: s.status,
      value: s.count,
      color: statusColor(s.status),
    }));
  }, [apiMetrics]);

  // Top routes horizontal bar chart data
  const routeBarData = useMemo(() => {
    if (!apiMetrics?.topRoutes?.length) return [];
    return apiMetrics.topRoutes.slice(0, 8).map(r => ({
      name: `${r.method} ${r.route}`.slice(0, 30),
      count: r.count,
    }));
  }, [apiMetrics]);

  if (loading && !summary) {
    return <div style={{ textAlign: 'center', padding: 80 }}><Spin size="large" /></div>;
  }

  return (
    <div>
      {/* === Welcome Banner === */}
      <Card
        style={{ marginBottom: 16, background: 'linear-gradient(135deg, #1890ff 0%, #722ed1 100%)', border: 'none' }}
        styles={{ body: { padding: isMobile ? '10px 12px' : '10px 16px' } }}
      >
        <Flex vertical={isMobile} gap={8}>
          <Flex justify="space-between" align="center" gap={8} style={{ minWidth: 0 }}>
            <Flex align="center" gap={8} style={{ minWidth: 0 }}>
              <Text strong style={{ color: '#fff', fontSize: 16, whiteSpace: 'nowrap' }}>
                Welcome{user?.name ? `, ${user.name}` : ''}
              </Text>
              <Text style={{ color: 'rgba(255,255,255,0.55)', fontSize: 12, whiteSpace: 'nowrap' }}>
                {lastRefresh && `Updated ${lastRefresh.toLocaleTimeString()}`}
              </Text>
            </Flex>
            {!isMobile && isSuperAdmin && homepageUrl && (
              <Segmented
                size="small"
                value={activeView}
                onChange={(val) => setActiveView(val as 'dashboard' | 'homepage')}
                options={[
                  { label: 'Dashboard', value: 'dashboard', icon: <DashboardOutlined /> },
                  { label: 'Homepage', value: 'homepage', icon: <HomeOutlined /> },
                ]}
                style={{ background: 'rgba(255,255,255,0.2)', borderRadius: 6, flexShrink: 0 }}
              />
            )}
          </Flex>
          {isMobile && isSuperAdmin && homepageUrl && (
            <Segmented
              size="small"
              value={activeView}
              onChange={(val) => setActiveView(val as 'dashboard' | 'homepage')}
              options={[
                { label: 'Dashboard', value: 'dashboard', icon: <DashboardOutlined /> },
                { label: 'Homepage', value: 'homepage', icon: <HomeOutlined /> },
              ]}
              style={{ background: 'rgba(255,255,255,0.2)', borderRadius: 6 }}
            />
          )}
          {activeView === 'dashboard' && (
            <Flex gap={4} wrap="wrap" justify={isMobile ? 'flex-start' : 'flex-end'} data-tour-dashboard-actions>
              {showInfluence && <Tooltip title="New Campaign"><Button type="text" icon={<PlusOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/campaigns')} /></Tooltip>}
              {showMap && <Tooltip title="Locations"><Button type="text" icon={<EnvironmentOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/map')} /></Tooltip>}
              {showMedia && <Tooltip title="Videos"><Button type="text" icon={<UploadOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/media/library')} /></Tooltip>}
              {!isMobile && <Tooltip title="Pages"><Button type="text" icon={<FileTextOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/pages')} /></Tooltip>}
              {isSuperAdmin && (
                <>
                  <Tooltip title="Monitoring"><Button type="text" icon={<BarChartOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/observability')} /></Tooltip>
                  {!isMobile && (
                    <>
                      <Tooltip title="Tunnel"><Button type="text" icon={<CloudServerOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/tunnel')} /></Tooltip>
                      <Tooltip title="NocoDB"><Button type="text" icon={<DatabaseOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/services/nocodb')} /></Tooltip>
                      <Tooltip title="Workflows"><Button type="text" icon={<BranchesOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/services/n8n')} /></Tooltip>
                      <Tooltip title="Git"><Button type="text" icon={<GlobalOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/services/gitea')} /></Tooltip>
                      <Tooltip title="Code"><Button type="text" icon={<CodeOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/code')} /></Tooltip>
                      <Tooltip title="Docs"><Button type="text" icon={<BookOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/docs')} /></Tooltip>
                      <Tooltip title="QR"><Button type="text" icon={<QrcodeOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/services/miniqr')} /></Tooltip>
                      <Tooltip title="Data Quality"><Button type="text" icon={<DashboardOutlined style={{ color: '#fff', fontSize: 18 }} />} onClick={() => navigate('/app/map/data-quality')} /></Tooltip>
                    </>
                  )}
                </>
              )}
              <Tooltip title="Refresh"><Button type="text" icon={<ReloadOutlined spin={loading} style={{ color: '#fff', fontSize: 18 }} />} onClick={handleRefresh} /></Tooltip>
            </Flex>
          )}
          {activeView === 'homepage' && (
            <Tooltip title="Refresh"><Button type="text" icon={<ReloadOutlined spin={loading} style={{ color: '#fff', fontSize: 18 }} />} onClick={handleRefresh} /></Tooltip>
          )}
        </Flex>
      </Card>

      {/* === Homepage iframe view === */}
      {activeView === 'homepage' && homepageUrl && (
        <iframe
          src={homepageUrl}
          style={{
            width: '100%',
            height: 'calc(100vh - 160px)',
            border: 'none',
            borderRadius: 8,
          }}
          title="Homepage Dashboard"
        />
      )}

      {/* === Dashboard view === */}
      {activeView === 'dashboard' && <>

      {/* === Onboarding Checklist === */}
      {!onboardingDismissed && summary && (() => {
        const items = [
          { label: 'Configure organization settings', path: '/app/settings', done: !!(settings?.organizationName && settings.organizationName !== 'Changemaker Lite'), show: true },
          { label: 'Create your first campaign', path: '/app/campaigns', done: (summary.campaigns.total ?? 0) > 0, show: showInfluence },
          { label: 'Import locations', path: '/app/map', done: (summary.locations.total ?? 0) > 0, show: showMap },
          { label: 'Create a volunteer shift', path: '/app/map/shifts', done: (summary.shifts.upcoming ?? 0) > 0, show: showMap },
          { label: 'Upload a video', path: '/app/media/library', done: (summary.videos?.total ?? 0) > 0, show: showMedia },
        ].filter(i => i.show);
        const doneCount = items.filter(i => i.done).length;
        if (doneCount >= items.length) return null;
        return (
          <Card
            size="small"
            style={{ marginBottom: 16 }}
            title={<><RocketOutlined style={{ marginRight: 6 }} />Getting Started</>}
            extra={
              <Space>
                <Tag color="blue">{doneCount}/{items.length} complete</Tag>
                <Button size="small" type="text" onClick={() => { setOnboardingDismissed(true); localStorage.setItem('cml-onboarding-dismissed', 'true'); }}>Dismiss</Button>
              </Space>
            }
          >
            <Space direction="vertical" style={{ width: '100%' }} size={4}>
              {items.map(item => (
                <div
                  key={item.path}
                  onClick={() => !item.done && navigate(item.path)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    padding: '6px 8px', borderRadius: 6,
                    cursor: item.done ? 'default' : 'pointer',
                    opacity: item.done ? 0.6 : 1,
                  }}
                >
                  <CheckCircleFilled style={{ color: item.done ? '#52c41a' : 'rgba(255,255,255,0.15)', fontSize: 16 }} />
                  <Text style={{ textDecoration: item.done ? 'line-through' : 'none' }}>{item.label}</Text>
                </div>
              ))}
            </Space>
          </Card>
        );
      })()}

      {/* === Status Bar (weather + stats + pending actions + connectivity) === */}
      {summary && (
        <Card size="small" style={{ marginBottom: 16 }} styles={{ body: { padding: isMobile ? '8px 10px' : '10px 16px' } }} data-tour-dashboard-stats>
          {isMobile ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {weather && (
                <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: 6, paddingBottom: 6, borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
                  <span style={{ fontSize: 22 }}>{getWeatherIcon(weather.weatherCode, weather.isDay)}</span>
                  <Text strong style={{ fontSize: 15 }}>{Math.round(weather.temperature)}°C</Text>
                  <Text type="secondary" style={{ fontSize: 12 }}>{weather.weatherDescription}</Text>
                </div>
              )}
              <MobileQuickStat icon={<TeamOutlined />} color="#1890ff" value={summary.users.total} label="Users" onClick={() => navigate('/app/users')} />
              {showInfluence && <MobileQuickStat icon={<SendOutlined />} color="#52c41a" value={summary.campaigns.active} label={`of ${summary.campaigns.total}`} onClick={() => navigate('/app/campaigns')} />}
              {showMap && <MobileQuickStat icon={<EnvironmentOutlined />} color="#722ed1" value={summary.locations.total.toLocaleString()} label={`${geocodePct}%`} onClick={() => navigate('/app/map')} />}
              {showInfluence && <MobileQuickStat icon={<MailOutlined />} color="#faad14" value={summary.emails.sent} label="sent" onClick={() => navigate('/app/email-queue')} />}
              {showMedia && <MobileQuickStat icon={<VideoCameraOutlined />} color="#13c2c2" value={summary.videos.published} label={`of ${summary.videos.total}`} onClick={() => navigate('/app/media/library')} />}
              {showMap && <MobileQuickStat icon={<ScheduleOutlined />} color="#eb2f96" value={summary.shifts.upcoming} label={`${summary.shifts.open} open`} onClick={() => navigate('/app/map/shifts')} />}
              {/* Pending action tags */}
              {(summary.responses.pending > 0 || (summary.locations.total > 0 && summary.locations.total - summary.locations.geocoded > 0) || summary.emails.queued > 0) && (
                <div style={{ gridColumn: '1 / -1', display: 'flex', flexWrap: 'wrap', gap: 4, paddingTop: 4, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
                  {summary.responses.pending > 0 && (
                    <Tag color="orange" style={{ cursor: 'pointer', margin: 0 }} onClick={() => navigate('/app/responses')}>
                      {summary.responses.pending} pending
                    </Tag>
                  )}
                  {summary.locations.total > 0 && summary.locations.total - summary.locations.geocoded > 0 && (
                    <Tag color="purple" style={{ cursor: 'pointer', margin: 0 }} onClick={() => navigate('/app/map')}>
                      {summary.locations.total - summary.locations.geocoded} ungeocoded
                    </Tag>
                  )}
                  {summary.emails.queued > 0 && (
                    <Tag color="blue" style={{ cursor: 'pointer', margin: 0 }} onClick={() => navigate('/app/email-queue')}>
                      {summary.emails.queued} queued
                    </Tag>
                  )}
                  {summary.campaignModeration.pendingReview > 0 && (
                    <Tag color="gold" style={{ cursor: 'pointer', margin: 0 }} onClick={() => navigate('/app/campaign-moderation')}>
                      {summary.campaignModeration.pendingReview} review
                    </Tag>
                  )}
                </div>
              )}
            </div>
          ) : (
            <Flex justify="space-between" align="center" wrap="wrap" gap={8}>
              <Flex gap={0} align="center" style={{ flexWrap: 'wrap' }}>
                {weather && (
                  <Flex align="center" gap={6} style={{ padding: '0 14px 0 0', borderRight: '1px solid rgba(255,255,255,0.08)' }}>
                    <span style={{ fontSize: 24 }}>{getWeatherIcon(weather.weatherCode, weather.isDay)}</span>
                    <Text strong style={{ fontSize: 16 }}>{Math.round(weather.temperature)}°C</Text>
                    <Text type="secondary" style={{ fontSize: 13 }}>{weather.weatherDescription}</Text>
                  </Flex>
                )}
                {/* Quick stat chips */}
                <QuickStat icon={<TeamOutlined />} color="#1890ff" value={summary.users.total} label="Users" onClick={() => navigate('/app/users')} />
                {showInfluence && <QuickStat icon={<SendOutlined />} color="#52c41a" value={summary.campaigns.active} label={`of ${summary.campaigns.total}`} onClick={() => navigate('/app/campaigns')} />}
                {showMap && <QuickStat icon={<EnvironmentOutlined />} color="#722ed1" value={summary.locations.total.toLocaleString()} label={`${geocodePct}% geo`} onClick={() => navigate('/app/map')} />}
                {showInfluence && <QuickStat icon={<MailOutlined />} color="#faad14" value={summary.emails.sent} label="sent" onClick={() => navigate('/app/email-queue')} />}
                {showMedia && <QuickStat icon={<VideoCameraOutlined />} color="#13c2c2" value={summary.videos.published} label={`of ${summary.videos.total}`} onClick={() => navigate('/app/media/library')} />}
                {showMap && <QuickStat icon={<ScheduleOutlined />} color="#eb2f96" value={summary.shifts.upcoming} label={`${summary.shifts.open} open`} onClick={() => navigate('/app/map/shifts')} />}
                {isSuperAdmin && grafanaUrl && (
                  <QuickStat icon={<BarChartOutlined />} color="#f5222d" value="Metrics" label="" onClick={() => window.open(`${grafanaUrl}/d/changemaker-overview?from=now-24h&to=now`, '_blank')} />
                )}
                {/* Pending action tags */}
                {summary.responses.pending > 0 && (
                  <Tag color="orange" style={{ cursor: 'pointer', margin: '0 0 0 4px' }} onClick={() => navigate('/app/responses')}>
                    {summary.responses.pending} pending
                  </Tag>
                )}
                {summary.locations.total > 0 && summary.locations.total - summary.locations.geocoded > 0 && (
                  <Tag color="purple" style={{ cursor: 'pointer', margin: '0 0 0 4px' }} onClick={() => navigate('/app/map')}>
                    {summary.locations.total - summary.locations.geocoded} ungeocoded
                  </Tag>
                )}
                {summary.emails.queued > 0 && (
                  <Tag color="blue" style={{ cursor: 'pointer', margin: '0 0 0 4px' }} onClick={() => navigate('/app/email-queue')}>
                    {summary.emails.queued} queued
                  </Tag>
                )}
                {summary.campaignModeration.pendingReview > 0 && (
                  <Tag color="gold" style={{ cursor: 'pointer', margin: '0 0 0 4px' }} onClick={() => navigate('/app/campaign-moderation')}>
                    {summary.campaignModeration.pendingReview} review
                  </Tag>
                )}
              </Flex>
              {isSuperAdmin && connectivity && (
                <Flex gap={6} align="center" style={{ flexShrink: 0 }}>
                  <ConnectivityDot label="SMTP" online={connectivity.smtp} />
                  <ConnectivityDot label="Listmonk" online={connectivity.listmonk} />
                  <ConnectivityDot label="Chat" online={connectivity.rocketchat} />
                  <ConnectivityDot label="Events" online={connectivity.gancio} />
                </Flex>
              )}
            </Flex>
          )}
        </Card>
      )}

      {/* === Email Queue Widget (shown if queue has items) === */}
      {queue && (queue.waiting > 0 || queue.active > 0 || queue.failed > 0) && (
        <Card
          size="small"
          style={{ marginBottom: 16, borderLeft: `4px solid ${queue.failed > 0 ? '#ff4d4f' : queue.paused ? '#faad14' : '#1890ff'}` }}
          styles={{ body: { padding: '6px 16px' } }}
        >
          <Flex justify="space-between" align="center" wrap="wrap" gap={8}>
            <Flex gap={16} align="center">
              <MailOutlined style={{ fontSize: 16, color: '#1890ff' }} />
              <div>
                <Text strong style={{ fontSize: 13 }}>Email Queue</Text>
                {queue.paused && <Tag color="red" style={{ marginLeft: 8 }}>Paused</Tag>}
              </div>
              <Space size={16}>
                <Statistic title={<Text style={{ fontSize: 10 }}>Waiting</Text>} value={queue.waiting} valueStyle={{ fontSize: 18 }} />
                <Statistic title={<Text style={{ fontSize: 10 }}>Active</Text>} value={queue.active} valueStyle={{ fontSize: 18, color: '#1890ff' }} />
                {queue.failed > 0 && (
                  <Statistic title={<Text style={{ fontSize: 10 }}>Failed</Text>} value={queue.failed} valueStyle={{ fontSize: 18, color: '#ff4d4f' }} />
                )}
              </Space>
            </Flex>
            <Button size="small" type="link" onClick={() => navigate('/app/email-queue')}>
              Manage Queue
            </Button>
          </Flex>
        </Card>
      )}

      {/* === Dashboard Cards (masonry layout for dense packing) === */}
      <div style={{ columnCount: screens.lg ? 3 : screens.md ? 2 : 1, columnGap: 16 }}>
        {showInfluence && (
          <div className="db-mi">
            <Card
              title={
                <Flex align="center" gap={6}>
                  <SendOutlined style={{ fontSize: 16 }} />
                  <span style={{ fontSize: 14 }}>Influence</span>
                  {summary && <Text type="secondary" style={{ fontSize: 13, fontWeight: 400 }}>{summary.campaigns.active} active / {summary.campaigns.total}</Text>}
                </Flex>
              }
              size="small"
              extra={
                <Space size={4}>
                  {grafanaUrl && (
                    <Tooltip title="View email trends in Grafana">
                      <Button type="text" size="small" icon={<LineChartOutlined />} onClick={() => window.open(`${grafanaUrl}/d/changemaker-overview?viewPanel=2&from=now-7d&to=now`, '_blank')} />
                    </Tooltip>
                  )}
                  <Button type="link" onClick={() => navigate('/app/campaigns')}>View</Button>
                </Space>
              }
            >
              {summary && (
                <Flex gap={8} align="flex-start">
                  <Space direction="vertical" style={{ width: '100%', flex: 1 }} size={6}>
                    <Flex gap={4} wrap="wrap">
                      <Tag color="green">{summary.campaigns.active} Active</Tag>
                      <Tag>{summary.campaigns.draft} Draft</Tag>
                      {summary.campaigns.paused > 0 && <Tag color="orange">{summary.campaigns.paused} Paused</Tag>}
                    </Flex>
                    <Flex justify="space-between">
                      <Text style={{ fontSize: 13 }}>Responses: <Text strong>{summary.responses.total}</Text></Text>
                      {summary.responses.pending > 0 && <Tag color="orange" style={{ margin: 0 }}>{summary.responses.pending} pending</Tag>}
                    </Flex>
                    <Flex justify="space-between">
                      <Text style={{ fontSize: 13 }}>Emails: <Text strong>{summary.emails.sent}</Text> sent</Text>
                      {summary.emails.failed > 0 && <Text type="danger">{summary.emails.failed} failed</Text>}
                    </Flex>
                    {queue && (
                      <Flex justify="space-between">
                        <Text style={{ fontSize: 13 }}>Queue: <Text strong>{queue.waiting}</Text> waiting</Text>
                        {queue.paused && <Tag color="red" style={{ margin: 0 }}>Paused</Tag>}
                      </Flex>
                    )}
                  </Space>
                  {summary.campaigns.total > 0 && screens.md && (
                    <div style={{ width: 90, flexShrink: 0 }}>
                      <MiniDonutChart data={campaignDonutData} height={90} innerRadius={22} outerRadius={38} />
                    </div>
                  )}
                </Flex>
              )}
            </Card>
          </div>
        )}

        {showMap && (
          <div className="db-mi">
            <Card
              title={
                <Flex align="center" gap={6}>
                  <CompassOutlined style={{ fontSize: 16 }} />
                  <span style={{ fontSize: 14 }}>Map</span>
                  {summary && <Text type="secondary" style={{ fontSize: 13, fontWeight: 400 }}>{summary.locations.total.toLocaleString()} locations</Text>}
                </Flex>
              }
              size="small"
              extra={
                <Space size={4}>
                  {grafanaUrl && (
                    <Tooltip title="View canvass trends in Grafana">
                      <Button type="text" size="small" icon={<LineChartOutlined />} onClick={() => window.open(`${grafanaUrl}/d/changemaker-overview?viewPanel=10&from=now-7d&to=now`, '_blank')} />
                    </Tooltip>
                  )}
                  <Button type="link" onClick={() => navigate('/app/map')}>View</Button>
                </Space>
              }
            >
              {summary && (
                <Space direction="vertical" style={{ width: '100%' }} size={6}>
                  <Flex align="center" gap={8}>
                    <Text style={{ fontSize: 13 }}>Geocoded:</Text>
                    <Progress percent={geocodePct} size="small" style={{ flex: 1 }} />
                    <Text type="secondary" style={{ fontSize: 13 }}>{summary.locations.geocoded.toLocaleString()}/{summary.locations.total.toLocaleString()}</Text>
                  </Flex>
                  <Flex justify="space-between">
                    <Text style={{ fontSize: 13 }}>Addresses: <Text strong>{summary.locations.addresses.toLocaleString()}</Text></Text>
                    <Text type="secondary" style={{ fontSize: 13 }}><ScissorOutlined /> {summary.cuts.total} cuts</Text>
                  </Flex>
                  <Flex justify="space-between">
                    <Text style={{ fontSize: 13 }}>Canvassing: <Text strong>{summary.canvass.totalVisits}</Text> visits</Text>
                    {summary.canvass.activeSessions > 0 && <Tag color="green" style={{ margin: 0 }}>{summary.canvass.activeSessions} active</Tag>}
                  </Flex>
                  <Flex justify="space-between">
                    <Text style={{ fontSize: 13 }}>Shifts: <Text strong>{summary.shifts.upcoming}</Text> upcoming</Text>
                    <Text type="secondary" style={{ fontSize: 13 }}>{summary.shifts.open} open</Text>
                  </Flex>
                </Space>
              )}
            </Card>
          </div>
        )}

        <div className="db-mi">
          <Card
            title={
              <Flex align="center" gap={6}>
                <TeamOutlined style={{ fontSize: 16 }} />
                <span style={{ fontSize: 14 }}>Users & Content</span>
                {summary && <Text type="secondary" style={{ fontSize: 13, fontWeight: 400 }}>{summary.users.total} users</Text>}
              </Flex>
            }
            size="small"
            extra={
              <Space size={4}>
                {grafanaUrl && (
                  <Tooltip title="View login trends in Grafana">
                    <Button type="text" size="small" icon={<LineChartOutlined />} onClick={() => window.open(`${grafanaUrl}/d/changemaker-overview?viewPanel=5&from=now-7d&to=now`, '_blank')} />
                  </Tooltip>
                )}
                <Button type="link" onClick={() => navigate('/app/users')}>Manage</Button>
              </Space>
            }
          >
            {summary && (
              <Space direction="vertical" style={{ width: '100%' }} size={6}>
                <Flex gap={4} wrap="wrap">
                  {Object.entries(summary.users.byRole)
                    .filter(([, count]) => count > 0)
                    .map(([role, count]) => (
                      <Tag key={role} color={ROLE_COLORS[role] || 'default'} style={{ margin: 0 }}>
                        {ROLE_LABELS[role] || role}: {count}
                      </Tag>
                    ))}
                  {summary.users.suspended > 0 && <Tag color="volcano" style={{ margin: 0 }}>Suspended: {summary.users.suspended}</Tag>}
                </Flex>
                <Flex justify="space-between">
                  <Text style={{ fontSize: 13 }}>Pages: <Text strong>{summary.pages.published}</Text> published</Text>
                  <Text type="secondary" style={{ fontSize: 13 }}>/ {summary.pages.total}</Text>
                </Flex>
                <Flex justify="space-between">
                  <Text style={{ fontSize: 13 }}>Templates: <Text strong>{summary.emailTemplates.total}</Text></Text>
                  {showInfluence && <Text type="secondary" style={{ fontSize: 13 }}>Reps: {summary.representatives.totalCached}</Text>}
                </Flex>
                {showMedia && (
                  <Flex justify="space-between">
                    <Text style={{ fontSize: 13 }}>Videos: <Text strong>{summary.videos.published}</Text> published</Text>
                    <Text type="secondary" style={{ fontSize: 13 }}>/ {summary.videos.total}</Text>
                  </Flex>
                )}
              </Space>
            )}
          </Card>
        </div>

        <div className="db-mi" data-tour-dashboard-activity>
          <ActivityFeedCard />
        </div>
        {showEvents && (
          <div className="db-mi">
            <TodayEventsCard />
          </div>
        )}
        <div className="db-mi">
          <DocsAnalyticsCard />
        </div>
        {showChat && (
          <div className="db-mi">
            <ChatNotifierCard />
          </div>
        )}
        {showMap && (
          <div className="db-mi">
            <UpcomingShiftsCard />
          </div>
        )}
        {settings?.enableMeetingPlanner && (
          <div className="db-mi">
            <MyActionItemsCard />
          </div>
        )}
        {showMeet && (
          <div className="db-mi">
            <UpcomingMeetingsCard />
          </div>
        )}
        {showInfluence && (
          <div className="db-mi">
            <CampaignEffectivenessCard />
          </div>
        )}
        {showMap && (
          <div className="db-mi">
            <RecentSignupsCard />
          </div>
        )}
        {showMedia && (
          <div className="db-mi">
            <TopVideosCard />
          </div>
        )}
        {showMedia && (
          <div className="db-mi">
            <RecentCommentsCard />
          </div>
        )}
        {showNewsletter && isSuperAdmin && (
          <div className="db-mi">
            <NewsletterStatsCard />
          </div>
        )}
        {showPayments && isSuperAdmin && (
          <div className="db-mi">
            <DonationSummaryCard />
          </div>
        )}
        {isSuperAdmin && (
          <div className="db-mi">
            <SystemAlertsCard />
          </div>
        )}
        {isSuperAdmin && (
          <div className="db-mi">
            <GiteaActivityCard />
          </div>
        )}
        {isSuperAdmin && (
          <div className="db-mi">
            <VaultwardenAdoptionCard />
          </div>
        )}
      </div>

      {/* === Canvass Progress (full-width table) === */}
      {showMap && (
        <Row gutter={[16, 16]} style={{ marginTop: 16, marginBottom: 16 }}>
          <Col xs={24}>
            <CutCampaignAnalyticsCard />
          </Col>
        </Row>
      )}

      {/* === System + Docker Section (SUPER_ADMIN only) === */}
      {isSuperAdmin && (
        <>
          {/* === Time-Series Charts (Traffic + Latency) === */}
          {timeSeries && screens.md && (
            <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
              <Col xs={24} lg={12}>
                <Card
                  title={<><BarChartOutlined style={{ marginRight: 6 }} />Request Traffic (1h)</>}
                  size="small"
                  style={{ height: '100%' }}
                >
                  <RequestTrafficChart data={timeSeries} height={200} />
                </Card>
              </Col>
              <Col xs={24} lg={12}>
                <Card
                  title={<><ApiOutlined style={{ marginRight: 6 }} />Latency Percentiles (1h)</>}
                  size="small"
                  style={{ height: '100%' }}
                >
                  <LatencyBandsChart data={timeSeries} height={200} />
                </Card>
              </Col>
            </Row>
          )}

          {/* System Info + Service Health */}
          <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
            {/* Hardware card with circular gauges + mini system chart */}
            <Col xs={24} lg={8}>
              <Card title={<><DesktopOutlined style={{ marginRight: 6 }} />System</>} size="small" style={{ height: '100%' }}>
                {systemInfo ? (
                  <Space direction="vertical" style={{ width: '100%' }} size={8}>
                    {/* Circular gauges */}
                    <SystemGauges systemInfo={systemInfo} />

                    {/* System load mini area chart */}
                    {timeSeries?.cpu_usage?.timestamps?.length ? (
                      <MiniSystemChart timeSeries={timeSeries} />
                    ) : null}

                    {/* Text details */}
                    <div style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 8 }}>
                      <Flex justify="space-between">
                        <Text type="secondary" style={{ fontSize: 11 }}>Host</Text>
                        <Text style={{ fontSize: 11 }}>{systemInfo.hostname}</Text>
                      </Flex>
                      <Flex justify="space-between">
                        <Text type="secondary" style={{ fontSize: 11 }}>CPU</Text>
                        <Text style={{ fontSize: 11 }}>{systemInfo.cpu.cores} cores &middot; Load {systemInfo.cpu.loadAvg[0]}</Text>
                      </Flex>
                      <Flex justify="space-between">
                        <Text type="secondary" style={{ fontSize: 11 }}>Memory</Text>
                        <Text style={{ fontSize: 11 }}>{Math.round(systemInfo.memory.usedMB / 1024 * 10) / 10}/{Math.round(systemInfo.memory.totalMB / 1024)}GB</Text>
                      </Flex>
                      <Flex justify="space-between">
                        <Text type="secondary" style={{ fontSize: 11 }}>Uptime</Text>
                        <Text style={{ fontSize: 11 }}>{formatUptime(systemInfo.uptime)}</Text>
                      </Flex>
                      <Flex justify="space-between">
                        <Text type="secondary" style={{ fontSize: 11 }}>API Process</Text>
                        <Text style={{ fontSize: 11 }}>{systemInfo.process.rssMB}MB RSS &middot; {formatUptime(systemInfo.process.uptimeSeconds)}</Text>
                      </Flex>
                    </div>
                  </Space>
                ) : <Spin size="small" />}
              </Card>
            </Col>

            {/* Infrastructure: service health + docker containers unified */}
            <Col xs={24} lg={16}>
              <Card
                title={<><ContainerOutlined style={{ marginRight: 6 }} />Infrastructure</>}
                size="small"
                style={{ height: '100%' }}
                data-tour-dashboard-services
                extra={
                  <Flex gap={8} align="center">
                    {health && (
                      <Tag color={health.status === 'healthy' ? 'green' : 'red'} style={{ marginRight: 0 }}>
                        {health.status === 'healthy' ? 'Core OK' : 'Degraded'}
                      </Tag>
                    )}
                    {containers && (
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        {containers.filter(c => c.running).length}/{containers.length} running
                      </Text>
                    )}
                  </Flex>
                }
              >
                {/* Core services row */}
                <Flex gap={6} wrap="wrap" style={{ marginBottom: 10 }}>
                  <ServiceBadge name="API" online={!!health} icon={<RocketOutlined />} />
                  <ServiceBadge name="Database" online={health?.checks.database === 'ok'} icon={<DatabaseOutlined />} />
                  <ServiceBadge name="Redis" online={health?.checks.redis === 'ok'} icon={<HddOutlined />} />
                  {services && Object.entries(services).map(([key, svc]) => (
                    <ServiceBadge
                      key={key}
                      name={SERVICE_LABELS[key] || key}
                      online={svc.online}
                      icon={SERVICE_ICONS[key] || <CloudServerOutlined />}
                    />
                  ))}
                </Flex>

                {/* Container tiles */}
                {containers ? (
                  <>
                    <Row gutter={[6, 6]}>
                      {containers.map(c => {
                        const tile = containerTileBg(c.running, c.status);
                        return (
                          <Col xs={12} sm={8} md={6} lg={6} xl={4} key={c.name}>
                            <ContainerPopover resource={containerResourceMap.get(c.name)}>
                              <Tooltip title={`${c.name} \u2014 ${c.status}`}>
                                <div style={{
                                  padding: '5px 6px',
                                  borderRadius: 6,
                                  background: tile.bg,
                                  border: `1px solid ${tile.border}`,
                                  textAlign: 'center',
                                  cursor: containerResourceMap.has(c.name) ? 'pointer' : 'default',
                                  transition: 'transform 0.15s',
                                }}
                                onMouseEnter={e => (e.currentTarget.style.transform = 'scale(1.03)')}
                                onMouseLeave={e => (e.currentTarget.style.transform = 'scale(1)')}
                                >
                                  {c.running
                                    ? <CheckCircleFilled style={{ color: '#52c41a', fontSize: 11, marginRight: 3 }} />
                                    : c.status === 'not_found'
                                      ? <MinusCircleFilled style={{ color: '#999', fontSize: 11, marginRight: 3 }} />
                                      : <CloseCircleFilled style={{ color: '#ff4d4f', fontSize: 11, marginRight: 3 }} />
                                  }
                                  <Text style={{ fontSize: 11 }}>{c.label}</Text>
                                </div>
                              </Tooltip>
                            </ContainerPopover>
                          </Col>
                        );
                      })}
                    </Row>
                    {/* Container Memory Bar Chart */}
                    {containerResources && containerResources.length > 0 && screens.md && (
                      <div style={{ marginTop: 10 }}>
                        <Text type="secondary" style={{ fontSize: 11, display: 'block', marginBottom: 4 }}>Container Memory Usage</Text>
                        <ContainerMemoryChart containers={containerResources} height={Math.min(containerResources.filter(c => c.memoryMB > 0).length * 22 + 36, 280)} />
                      </div>
                    )}
                  </>
                ) : <Spin size="small" />}
              </Card>
            </Col>
          </Row>

          {/* API Performance with status code donut + route bar chart */}
          {apiMetrics && (
            <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
              <Col xs={24} lg={12}>
                <Card
                  title={<><ApiOutlined style={{ marginRight: 6 }} />API Performance</>}
                  size="small"
                  style={{ height: '100%' }}
                  extra={
                    <Flex gap={12}>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        {apiMetrics.requestRate.toFixed(1)} req/s
                      </Text>
                      <Text type={apiMetrics.errorRate > 5 ? 'danger' : 'secondary'} style={{ fontSize: 12 }}>
                        {apiMetrics.errorRate.toFixed(1)}% errors
                      </Text>
                    </Flex>
                  }
                >
                  <Flex gap={12} align="flex-start">
                    <Space direction="vertical" size={4} style={{ flex: 1 }}>
                      <Flex gap={16} wrap="wrap">
                        <Statistic
                          title={<Text style={{ fontSize: 12 }}>Avg Latency</Text>}
                          value={apiMetrics.avgLatencyMs}
                          suffix="ms"
                          valueStyle={{ fontSize: 18, color: apiMetrics.avgLatencyMs > 500 ? '#ff4d4f' : apiMetrics.avgLatencyMs > 200 ? '#faad14' : '#52c41a' }}
                        />
                        <Statistic
                          title={<Text style={{ fontSize: 12 }}>P95 Latency</Text>}
                          value={apiMetrics.p95LatencyMs}
                          suffix="ms"
                          valueStyle={{ fontSize: 18, color: apiMetrics.p95LatencyMs > 1000 ? '#ff4d4f' : apiMetrics.p95LatencyMs > 500 ? '#faad14' : '#52c41a' }}
                        />
                      </Flex>
                      {/* Slow routes */}
                      {apiMetrics.slowRoutes.length > 0 && (
                        <div style={{ marginTop: 4 }}>
                          <Text type="secondary" style={{ fontSize: 11 }}>Slowest Routes (P95)</Text>
                          {apiMetrics.slowRoutes.slice(0, 3).map((r, i) => (
                            <Flex key={i} justify="space-between" style={{ padding: '2px 0' }}>
                              <Text style={{ fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '65%' }}>
                                <Tag style={{ fontSize: 9, padding: '0 3px', marginRight: 3 }}>{r.method}</Tag>
                                {r.route}
                              </Text>
                              <Text type="danger" style={{ fontSize: 11 }}>{r.p95Ms.toFixed(0)}ms</Text>
                            </Flex>
                          ))}
                        </div>
                      )}
                    </Space>
                    {/* Status code donut */}
                    {statusDonutData.length > 0 && screens.sm && (
                      <div style={{ width: 110, flexShrink: 0 }}>
                        <MiniDonutChart data={statusDonutData} height={110} innerRadius={26} outerRadius={46} />
                      </div>
                    )}
                  </Flex>
                </Card>
              </Col>

              <Col xs={24} lg={12}>
                <Card
                  title={<><BarChartOutlined style={{ marginRight: 6 }} />Top Routes</>}
                  size="small"
                  style={{ height: '100%' }}
                >
                  {routeBarData.length > 0 ? (
                    <ResponsiveContainer width="100%" height={Math.max(routeBarData.length * 24 + 20, 120)}>
                      <BarChart data={routeBarData} layout="vertical" margin={{ top: 0, right: 16, left: 4, bottom: 0 }}>
                        <XAxis type="number" tick={{ fontSize: 10 }} />
                        <YAxis type="category" dataKey="name" tick={{ fontSize: 10 }} width={isMobile ? 80 : 120} />
                        <RechartsTooltip contentStyle={{ fontSize: 12, borderRadius: 6 }} />
                        <Bar dataKey="count" radius={[0, 4, 4, 0]}>
                          {routeBarData.map((_, i) => (
                            <Cell key={i} fill={['#1890ff', '#13c2c2', '#722ed1', '#52c41a', '#faad14', '#eb2f96', '#fa8c16', '#2f54eb'][i % 8]} />
                          ))}
                        </Bar>
                      </BarChart>
                    </ResponsiveContainer>
                  ) : (
                    <Text type="secondary">No route data yet</Text>
                  )}
                </Card>
              </Col>
            </Row>
          )}

        </>
      )}

      </>}
      <PageTour sectionId="dashboard" />
    </div>
  );
}

// --- Mini System Load Chart (CPU + Memory over 1h) ---

import { AreaChart, Area, XAxis as AreaXAxis } from 'recharts';

function MiniSystemChart({ timeSeries }: { timeSeries: TimeSeriesResult }) {
  const cpu = timeSeries.cpu_usage;
  const mem = timeSeries.memory_usage;
  if (!cpu?.timestamps?.length) return null;

  const data = cpu.timestamps.map((ts, i) => ({
    t: new Date(ts * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
    cpu: Math.round(cpu.values[i] || 0),
    mem: Math.round(mem?.values[i] || 0),
  }));

  return (
    <ResponsiveContainer width="100%" height={70}>
      <AreaChart data={data} margin={{ top: 2, right: 2, left: 2, bottom: 0 }}>
        <AreaXAxis dataKey="t" hide />
        <RechartsTooltip contentStyle={{ fontSize: 11, borderRadius: 6 }} formatter={(v, n) => [`${v}%`, n === 'cpu' ? 'CPU' : 'Memory']} />
        <Area type="monotone" dataKey="cpu" stroke="#1890ff" fill="#1890ff" fillOpacity={0.2} strokeWidth={1.5} />
        <Area type="monotone" dataKey="mem" stroke="#722ed1" fill="#722ed1" fillOpacity={0.15} strokeWidth={1.5} />
      </AreaChart>
    </ResponsiveContainer>
  );
}


// --- Service Badge Component (with pulse animation) ---

const SERVICE_LABELS: Record<string, string> = {
  nocodb: 'NocoDB',
  n8n: 'n8n',
  gitea: 'Gitea',
  mailhog: 'MailHog',
  miniqr: 'Mini QR',
  excalidraw: 'Excalidraw',
  homepage: 'Homepage',
  vaultwarden: 'Vaultwarden',
  rocketchat: 'Rocket.Chat',
  gancio: 'Gancio',
  jitsi: 'Jitsi Meet',
};

const SERVICE_ICONS: Record<string, React.ReactNode> = {
  nocodb: <DatabaseOutlined />,
  n8n: <BranchesOutlined />,
  gitea: <GlobalOutlined />,
  mailhog: <MailOutlined />,
  miniqr: <QrcodeOutlined />,
  excalidraw: <FileTextOutlined />,
  homepage: <HomeOutlined />,
  vaultwarden: <LockOutlined />,
  rocketchat: <MessageOutlined />,
  gancio: <CalendarOutlined />,
  jitsi: <VideoCameraOutlined />,
};

// --- Quick Stat chip (for status bar) ---

function QuickStat({ icon, color, value, label, onClick }: {
  icon: React.ReactNode;
  color: string;
  value: string | number;
  label: string;
  onClick: () => void;
}) {
  return (
    <Flex
      align="center"
      gap={6}
      onClick={onClick}
      style={{
        padding: '2px 12px',
        cursor: 'pointer',
        borderRight: '1px solid rgba(255,255,255,0.06)',
      }}
    >
      <span style={{ color, fontSize: 16 }}>{icon}</span>
      <Text strong style={{ fontSize: 16 }}>{value}</Text>
      <Text type="secondary" style={{ fontSize: 13 }}>{label}</Text>
    </Flex>
  );
}

function MobileQuickStat({ icon, color, value, label, onClick }: {
  icon: React.ReactNode;
  color: string;
  value: string | number;
  label: string;
  onClick: () => void;
}) {
  return (
    <div
      onClick={onClick}
      style={{
        display: 'flex',
        alignItems: 'center',
        gap: 6,
        padding: '6px 8px',
        cursor: 'pointer',
        borderRadius: 6,
        background: 'rgba(255,255,255,0.04)',
      }}
    >
      <span style={{ color, fontSize: 15 }}>{icon}</span>
      <Text strong style={{ fontSize: 15 }}>{value}</Text>
      <Text type="secondary" style={{ fontSize: 11 }}>{label}</Text>
    </div>
  );
}

function ConnectivityDot({ label, online }: { label: string; online: boolean }) {
  return (
    <Tooltip title={`${label}: ${online ? 'Connected' : 'Offline'}`}>
      <Flex gap={3} align="center">
        <div style={{
          width: 8, height: 8, borderRadius: '50%',
          background: online ? '#52c41a' : '#ff4d4f',
        }} />
        <Text style={{ fontSize: 11 }}>{label}</Text>
      </Flex>
    </Tooltip>
  );
}

function ServiceBadge({ name, online, icon }: {
  name: string;
  online?: boolean;
  icon: React.ReactNode;
}) {
  return (
    <Tooltip title={online ? 'Online' : online === false ? 'Offline' : 'Unknown'}>
      <div style={{ textAlign: 'center', padding: '4px 0' }} className={online ? 'svc-badge-online' : ''}>
        <Badge
          status={online ? 'success' : online === false ? 'error' : 'default'}
          text={
            <span style={{ fontSize: 11 }}>
              {icon} {name}
            </span>
          }
        />
      </div>
    </Tooltip>
  );
}
