import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import fidoKeyService from '../services/fidoKeyService';
import ticketService from '../services/ticketService';
import assetService from '../services/assetService';
import onboardingService from '../services/onboardingService';
import offboardingService from '../services/offboardingService';
import userService from '../services/userService';
import licenseService from '../services/licenseService';
import warehouseService from '../services/warehouseService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';

const API = process.env.REACT_APP_API_URL || '/api';
const authFetch = (url) =>
    fetch(url, { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } })
        .then(r => r.ok ? r.json() : null).catch(() => null);

const today = new Date();
const hour = today.getHours();
const greeting = hour < 12 ? 'Guten Morgen' : hour < 17 ? 'Guten Tag' : 'Guten Abend';
const dateStr = today.toLocaleDateString('de-DE', { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' });

const circumference = 2 * Math.PI * 42;

const actionPillClass = (action = '') => {
    if (action.startsWith('CREATE')) return 'create';
    if (action.startsWith('DELETE')) return 'delete';
    return 'update';
};

const actionPillLabel = (action = '') => {
    if (action.startsWith('CREATE')) return `＋ ${action}`;
    if (action.startsWith('DELETE')) return `✕ ${action}`;
    return `↻ ${action}`;
};

const avatarColors = ['var(--cereda-primary)', '#007aff', '#af52de', '#ff9500', '#34c759', '#ff3b30'];
const getAvatarColor = (str = '') => avatarColors[str.charCodeAt(0) % avatarColors.length];

/* ═══════════════════════════════════════════════════════════════════
   DashboardPage
═══════════════════════════════════════════════════════════════════ */
const DashboardPage = () => {
    const { user, isSuperAdmin, isAdmin } = useAuth();

    const [fidoStats,        setFidoStats]        = useState(null);
    const [assetStats,       setAssetStats]       = useState(null);
    const [ticketStats,      setTicketStats]      = useState(null);
    const [maintenanceStats, setMaintenanceStats] = useState(null);
    const [licenseStats,     setLicenseStats]     = useState(null);
    const [onboardingStats,  setOnboardingStats]  = useState(null);
    const [offboardingStats, setOffboardingStats] = useState(null);
    const [recentLogs,       setRecentLogs]       = useState([]);
    const [ticketMetrics,    setTicketMetrics]    = useState(null);
    const [stockViolations,  setStockViolations]  = useState([]);

    const [monitoringStats,  setMonitoringStats]  = useState(null);
    const [patchStats,       setPatchStats]       = useState(null);
    const [lastSecReport,    setLastSecReport]    = useState(null);
    const [announcements,    setAnnouncements]    = useState([]);
    const [shareCount,       setShareCount]       = useState(null);

    const [logFilter, setLogFilter] = useState('Alle');
    const [loading, setLoading] = useState(true);

    useEffect(() => { loadDashboardData(); }, []);

    const loadDashboardData = async () => {
        try {
            const fStats = await fidoKeyService.getStatistics();
            setFidoStats(fStats);

            try { const tStats = await ticketService.getStats(); setTicketStats(tStats); const tMetrics = await ticketService.getMetrics(30); setTicketMetrics(tMetrics); } catch { /* */ }
            try {
                const aStats = await assetService.getStatistics(); setAssetStats(aStats);
                const allAssets = await assetService.getAll();
                const todayStr = new Date().toISOString().slice(0, 10);
                const in30Str  = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);
                const overdue  = allAssets.filter(a => a.next_maintenance_date && a.next_maintenance_date <= todayStr).length;
                const upcoming = allAssets.filter(a => a.next_maintenance_date && a.next_maintenance_date > todayStr && a.next_maintenance_date <= in30Str).length;
                if (overdue > 0 || upcoming > 0) setMaintenanceStats({ overdue, upcoming });
            } catch { /* */ }
            try { const lStats = await licenseService.getStatistics(); if (lStats.expired > 0 || lStats.expiringSoon > 0) setLicenseStats(lStats); } catch { /* */ }

            if (isAdmin()) {
                try { const s = await onboardingService.getStatistics();  setOnboardingStats(s);  } catch { /* */ }
                try { const s = await offboardingService.getStatistics(); setOffboardingStats(s); } catch { /* */ }
                try { const logs = await userService.getAuditLogs(10, 0); setRecentLogs(logs); }  catch { /* */ }
                try { const v = await warehouseService.getViolations(); setStockViolations(v); } catch { /* */ }

                const monData = await authFetch(`${API}/monitoring`);
                if (monData) {
                    const agents = Array.isArray(monData) ? monData : (monData.data || monData.agents || []);
                    const now = Date.now();
                    const online  = agents.filter(a => a.last_checkin && (now - new Date(a.last_checkin + 'Z').getTime()) < 15 * 60 * 1000).length;
                    const offline = agents.length - online;
                    const pendingUpdates = agents.reduce((s, a) => s + (a.windows_updates_pending || 0), 0);
                    const noEncrypt = agents.filter(a => a.bitlocker_status && a.bitlocker_status !== 'encrypted').length;
                    setMonitoringStats({ total: agents.length, online, offline, pendingUpdates, noEncrypt });
                }

                const patchData = await authFetch(`${API}/patch/overview`);
                if (patchData?.stats) setPatchStats(patchData.stats);

                const secData = await authFetch(`${API}/security-reports`);
                if (secData?.length > 0) setLastSecReport(secData[0]);

                const annData = await authFetch(`${API}/announcements`);
                if (Array.isArray(annData)) setAnnouncements(annData.filter(a => a.active).slice(0, 3));

                const sharesData = await authFetch(`${API}/shares`);
                if (Array.isArray(sharesData)) {
                    const now = Date.now();
                    const active = sharesData.filter(s => {
                        if (s.expires_at && new Date(s.expires_at + 'Z') < new Date()) return false;
                        if (s.max_downloads && s.download_count >= s.max_downloads) return false;
                        return true;
                    }).length;
                    const expiringSoon = sharesData.filter(s => {
                        if (!s.expires_at) return false;
                        const exp = new Date(s.expires_at + 'Z');
                        if (exp < new Date()) return false;
                        return (exp - now) < 7 * 86400 * 1000;
                    }).length;
                    setShareCount({ total: sharesData.length, active, expiringSoon });
                }
            }
        } catch { toast.error('Fehler beim Laden der Dashboard-Daten'); }
        finally { setLoading(false); }
    };

    if (loading) return <div className="main-content"><LoadingSpinner /></div>;

    const patchPct = patchStats ? Math.round((patchStats.compliant || 0) / Math.max(patchStats.total || 1, 1) * 100) : 0;
    const dashoffset = circumference * (1 - patchPct / 100);
    const agentOnlinePct = monitoringStats?.total > 0 ? (monitoringStats.online / monitoringStats.total * 100).toFixed(1) : 0;

    const riskLevel = lastSecReport?.risk_level || 'unbekannt';
    const riskClass = riskLevel === 'hoch' ? 'risk-high' : riskLevel === 'mittel' ? 'risk-mid' : '';
    const riskLabel = riskLevel === 'hoch' ? 'Hohes Risiko' : riskLevel === 'mittel' ? 'Mittleres Risiko' : 'Niedriges Risiko';

    const filterMap = {
        'Alle': null, 'Assets': 'asset', 'Benutzer': 'user', 'Onboarding': 'onboarding_protocol', 'Tickets': 'ticket',
    };
    const filteredLogs = logFilter === 'Alle'
        ? recentLogs
        : recentLogs.filter(l => l.entity_type === filterMap[logFilter]);

    return (
        <div className="main-content">
            <div className="db-content">

                {/* ═══ HERO ═══ */}
                <section className="db-hero">
                    <div>
                        <div className="db-hero-date">{dateStr}</div>
                        <h1 className="db-hero-title">
                            {greeting}, <span className="db-accent">{user?.first_name || user?.username}.</span>
                        </h1>
                        <p className="db-hero-sub">
                            Ein Überblick über alle Systeme, Geräte und Vorgänge bei Cereda Systems — auf einen Blick.
                        </p>
                        <div className="db-hero-status">
                            <span className="db-pdot" />
                            {monitoringStats
                                ? `${monitoringStats.online} von ${monitoringStats.total} Agents online`
                                : 'System bereit'}
                        </div>
                    </div>
                    <div className="db-hero-actions">
                        <Link to="/tickets" className="db-btn">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M12 5v14M5 12h14"/>
                            </svg>
                            Neues Ticket
                        </Link>
                        {(isSuperAdmin() || isAdmin()) && (
                            <Link to="/monitoring" className="db-btn db-accent">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
                                </svg>
                                Monitoring
                            </Link>
                        )}
                    </div>
                </section>

                {/* ═══ ALERTS ═══ */}
                {(maintenanceStats?.overdue > 0 || licenseStats?.expiringSoon > 0 || licenseStats?.expired > 0 || (monitoringStats?.offline > 0)) && (
                    <div className="db-alerts">
                        {maintenanceStats?.overdue > 0 && (
                            <Link to="/assets?filter=maintenance" className="db-alert a-red">
                                <div className="db-ai">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                        <path d="M12 9v4M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                                    </svg>
                                </div>
                                <div>
                                    <div className="db-ah">Wartung überfällig <span className="db-ac">{maintenanceStats.overdue}</span></div>
                                    <div className="db-am">{maintenanceStats.overdue} Gerät{maintenanceStats.overdue > 1 ? 'e haben' : ' hat'} die planmäßige Wartung verpasst.</div>
                                    <span className="db-alink">Zu Assets →</span>
                                </div>
                            </Link>
                        )}
                        {(licenseStats?.expired > 0 || licenseStats?.expiringSoon > 0) && (
                            <Link to="/licenses" className="db-alert a-amber">
                                <div className="db-ai">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                        <circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>
                                    </svg>
                                </div>
                                <div>
                                    <div className="db-ah">Lizenzen ablaufend <span className="db-ac">{(licenseStats.expired || 0) + (licenseStats.expiringSoon || 0)}</span></div>
                                    <div className="db-am">{licenseStats.expired > 0 ? `${licenseStats.expired} abgelaufen · ` : ''}{licenseStats.expiringSoon > 0 ? `${licenseStats.expiringSoon} in 30 Tagen` : ''}</div>
                                    <span className="db-alink">Lizenzen prüfen →</span>
                                </div>
                            </Link>
                        )}
                        {monitoringStats?.offline > 0 && (
                            <Link to="/monitoring" className="db-alert a-blue">
                                <div className="db-ai">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                        <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
                                    </svg>
                                </div>
                                <div>
                                    <div className="db-ah">Geräte offline <span className="db-ac">{monitoringStats.offline}</span></div>
                                    <div className="db-am">{monitoringStats.offline} Agent{monitoringStats.offline > 1 ? 's sind' : ' ist'} seit über 15 Min nicht erreichbar.</div>
                                    <span className="db-alink">Monitoring öffnen →</span>
                                </div>
                            </Link>
                        )}
                        {stockViolations.length > 0 && (
                            <Link to="/warehouse" className="db-alert a-amber">
                                <div className="db-ai">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                        <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8M16 6l-4-4-4 4M12 2v13"/>
                                    </svg>
                                </div>
                                <div>
                                    <div className="db-ah">Unter Mindestbestand <span className="db-ac">{stockViolations.length}</span></div>
                                    <div className="db-am">{stockViolations.map(v => `${v.category}: ${v.current_stock}/${v.min_stock}`).join(' · ')}</div>
                                    <span className="db-alink">Lager prüfen →</span>
                                </div>
                            </Link>
                        )}
                    </div>
                )}

                {/* ═══ SCHNELLZUGRIFF ═══ */}
                <div className="db-block">
                    <div className="db-section-head">
                        <div>
                            <h2>Schnellzugriff.</h2>
                            <p>Direkt zu den meistgenutzten Bereichen.</p>
                        </div>
                    </div>
                    <div className="db-quick-grid">
                        <Link to="/fido-keys" className="db-quick-card qc-key">
                            <div className="db-quick-icon">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15.5 7.5 3 3L22 7l-3-3M21 2l-9.6 9.6a5.5 5.5 0 1 1-2 2L19 4"/></svg>
                            </div>
                            <div className="db-quick-title">FIDO-Keys</div>
                            <div className="db-quick-sub">{fidoStats?.total || 0} gesamt · {fidoStats?.active || 0} aktiv</div>
                        </Link>
                        {(isSuperAdmin() || isAdmin()) && <>
                            <Link to="/assets" className="db-quick-card qc-asset">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="7" width="20" height="13" rx="2"/><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                                </div>
                                <div className="db-quick-title">Assets</div>
                                <div className="db-quick-sub">{assetStats?.total || 0} Geräte</div>
                            </Link>
                            <Link to="/tickets" className="db-quick-card qc-tix">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M3 10h18"/></svg>
                                </div>
                                <div className="db-quick-title">Tickets</div>
                                <div className="db-quick-sub">{ticketStats?.open || 0} offen</div>
                            </Link>
                            <Link to="/monitoring" className="db-quick-card qc-mon">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
                                </div>
                                <div className="db-quick-title">Monitoring</div>
                                <div className="db-quick-sub">{monitoringStats ? `${monitoringStats.online}/${monitoringStats.total} online` : 'Live-Status'}</div>
                            </Link>
                            <Link to="/patch-management" className="db-quick-card qc-patch">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v6M5 8l3 3M19 8l-3 3M3 14h18M5 20l4-4M19 20l-4-4M12 14v8"/></svg>
                                </div>
                                <div className="db-quick-title">Patches</div>
                                <div className="db-quick-sub">{patchStats ? `${patchPct} % konform` : 'Update-Rollout'}</div>
                            </Link>
                            <Link to="/security-reports" className="db-quick-card qc-sec">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>
                                </div>
                                <div className="db-quick-title">Security</div>
                                <div className="db-quick-sub">{lastSecReport ? riskLabel : 'M365 Reports'}</div>
                            </Link>
                            <Link to="/onboarding" className="db-quick-card qc-on">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><path d="M20 8v6M23 11h-6"/></svg>
                                </div>
                                <div className="db-quick-title">Onboarding</div>
                                <div className="db-quick-sub">{((onboardingStats?.pending || 0) + (onboardingStats?.in_progress || 0))} offen</div>
                            </Link>
                            <Link to="/users" className="db-quick-card qc-usr">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                                </div>
                                <div className="db-quick-title">Benutzer</div>
                                <div className="db-quick-sub">Rollen & Zugänge</div>
                            </Link>
                            <Link to="/licenses" className="db-quick-card qc-lic">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="3" width="16" height="18" rx="2"/><path d="M9 7h6M9 11h6M9 15h4"/></svg>
                                </div>
                                <div className="db-quick-title">Lizenzen</div>
                                <div className="db-quick-sub">{licenseStats?.expiringSoon > 0 ? `${licenseStats.expiringSoon} laufen ab` : 'Software & Ablauf'}</div>
                            </Link>
                            <a href="/share-tool.html" target="_blank" rel="noopener noreferrer" className="db-quick-card qc-share">
                                <div className="db-quick-icon">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8M16 6l-4-4-4 4M12 2v13"/></svg>
                                </div>
                                <div className="db-quick-title">Secure Share</div>
                                <div className="db-quick-sub">{shareCount ? `${shareCount.active} aktive Links` : 'Dateien teilen'}</div>
                            </a>
                        </>}
                    </div>
                </div>

                {/* ═══ KPI ÜBERSICHT ═══ */}
                <div className="db-block">
                    <div className="db-section-head">
                        <div>
                            <h2>Übersicht.</h2>
                            <p>Die wichtigsten Zahlen aus Helpdesk, Assets und IT.</p>
                        </div>
                    </div>
                    <div className="db-kpi-grid">
                        <Link to="/fido-keys" style={{ textDecoration: 'none' }}>
                            <div className="db-kpi k-key">
                                <div className="db-kpi-head">
                                    <div className="db-kpi-icon">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15.5 7.5 3 3L22 7l-3-3M21 2l-9.6 9.6a5.5 5.5 0 1 1-2 2L19 4"/></svg>
                                    </div>
                                    <span className="db-kpi-trend flat">→ 0</span>
                                </div>
                                <div className="db-kpi-value">{fidoStats?.total || 0}</div>
                                <div className="db-kpi-label">FIDO-Keys gesamt</div>
                                <div className="db-kpi-sub">{fidoStats?.active || 0} aktiv · {fidoStats?.assigned || 0} zugewiesen</div>
                            </div>
                        </Link>
                        {assetStats && (
                            <Link to="/assets" style={{ textDecoration: 'none' }}>
                                <div className="db-kpi k-asset">
                                    <div className="db-kpi-head">
                                        <div className="db-kpi-icon">
                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="7" width="20" height="13" rx="2"/><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                                        </div>
                                        <span className="db-kpi-trend up">↑ Bestand</span>
                                    </div>
                                    <div className="db-kpi-value">
                                        {assetStats?.verfuegbar || 0}<small> / {assetStats?.total || 0}</small>
                                    </div>
                                    <div className="db-kpi-label">Verfügbare Assets</div>
                                    <div className="db-kpi-sub">{assetStats?.zugewiesen || 0} zugewiesen · aktiv im Einsatz</div>
                                </div>
                            </Link>
                        )}
                        {ticketStats && (
                            <Link to="/tickets" style={{ textDecoration: 'none' }}>
                                <div className="db-kpi k-tix">
                                    <div className="db-kpi-head">
                                        <div className="db-kpi-icon">
                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M3 10h18"/></svg>
                                        </div>
                                        <span className={`db-kpi-trend ${ticketStats.open > 0 ? 'down' : 'flat'}`}>{ticketStats.open > 0 ? `↑ ${ticketStats.open}` : '→ 0'}</span>
                                    </div>
                                    <div className="db-kpi-value">{ticketStats?.open || 0}</div>
                                    <div className="db-kpi-label">Tickets offen</div>
                                    <div className="db-kpi-sub">{ticketStats?.inProgress || 0} in Bearbeitung · {ticketStats?.critical || 0} kritisch</div>
                                </div>
                            </Link>
                        )}
                        {onboardingStats && (
                            <Link to="/onboarding" style={{ textDecoration: 'none' }}>
                                <div className="db-kpi k-on">
                                    <div className="db-kpi-head">
                                        <div className="db-kpi-icon">
                                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><path d="M20 8v6M23 11h-6"/></svg>
                                        </div>
                                        <span className="db-kpi-trend flat">→ 0</span>
                                    </div>
                                    <div className="db-kpi-value">{(onboardingStats?.pending || 0) + (onboardingStats?.in_progress || 0)}</div>
                                    <div className="db-kpi-label">Onboardings offen</div>
                                    <div className="db-kpi-sub">{onboardingStats?.pending || 0} ausstehend · {onboardingStats?.in_progress || 0} aktiv</div>
                                </div>
                            </Link>
                        )}
                    </div>
                </div>

                {/* ═══ ASSET-TYPEN ═══ */}
                {assetStats && (
                    <div className="db-block">
                        <div className="db-section-head">
                            <div>
                                <h2>Asset-Typen.</h2>
                                <p>Verteilung der Geräte im Bestand.</p>
                            </div>
                            <Link to="/assets" className="db-btn">
                                Alle anzeigen
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 14, height: 14 }}><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                            </Link>
                        </div>
                        <div className="db-breakdown-grid">
                            {[
                                { cls: 'bd-note', label: 'Notebooks', value: assetStats?.byType?.notebook || 0, total: assetStats?.total || 1, icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="14" rx="2"/><path d="M2 20h20"/></svg> },
                                { cls: 'bd-mon',  label: 'Monitore',  value: assetStats?.byType?.monitor  || 0, total: assetStats?.total || 1, icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg> },
                                { cls: 'bd-head', label: 'Headsets',  value: assetStats?.byType?.headset  || 0, total: assetStats?.total || 1, icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 18v-6a9 9 0 0 1 18 0v6"/><path d="M21 19a2 2 0 0 1-2 2h-1v-7h3zM3 19a2 2 0 0 0 2 2h1v-7H3z"/></svg> },
                                { cls: 'bd-other', label: 'Sonstiges', value: assetStats?.byType?.other   || 0, total: assetStats?.total || 1, icon: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="7" width="20" height="13" rx="2"/><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> },
                            ].map(({ cls, label, value, total, icon }) => {
                                const pct = Math.round(value / total * 100);
                                return (
                                    <div key={label} className={`db-breakdown ${cls}`}>
                                        <div className="db-breakdown-top">
                                            <div className="db-breakdown-icon">{icon}</div>
                                            <div className="db-breakdown-name">{label}</div>
                                            <div className="db-breakdown-pct">{pct} %</div>
                                        </div>
                                        <div className="db-breakdown-num">{value}</div>
                                        <div className="db-breakdown-bar"><span style={{ width: `${pct}%` }} /></div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}

                {/* ═══ SYSTEM & SICHERHEIT ═══ */}
                {isAdmin() && (monitoringStats || patchStats || lastSecReport || shareCount !== null) && (
                    <div className="db-block">
                        <div className="db-section-head">
                            <div>
                                <h2>System & Sicherheit.</h2>
                                <p>Status aus Monitoring, Patch-Management, Defender und Secure Share.</p>
                            </div>
                        </div>
                        <div className="db-info-grid">

                            {/* Feature: Ankündigungen */}
                            <div className="db-info-card db-feature">
                                <div className="db-info-eyebrow">
                                    <span className="db-ico">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 5L6 9H2v6h4l5 4V5zM19 12c0-2.5-1.5-5-4-6M22 12c0-4.5-3-8-7-9"/></svg>
                                    </span>
                                    Ankündigungen
                                </div>
                                <h3 className="db-info-title">Was gerade läuft.</h3>
                                <p className="db-info-sub">Aktuelle Mitteilungen und Roll-Outs für dein IT-Team.</p>
                                {announcements.length > 0 ? (
                                    <div className="db-announce-list">
                                        {announcements.map((ann, i) => {
                                            const initials = ((ann.created_by_name || ann.username || '?').split(' ').map(w => w[0]).join('').toUpperCase()).slice(0, 2);
                                            const avClass = i === 0 ? 'db-av' : i === 1 ? 'db-av s2' : 'db-av s3';
                                            const when = (() => {
                                                const d = new Date(ann.created_at);
                                                const diff = Date.now() - d.getTime();
                                                if (diff < 3600000) return `vor ${Math.round(diff / 60000)} Min`;
                                                if (diff < 86400000) return `vor ${Math.round(diff / 3600000)} h`;
                                                if (diff < 172800000) return 'gestern';
                                                return `vor ${Math.round(diff / 86400000)} Tagen`;
                                            })();
                                            return (
                                                <div key={ann.id} className="db-announce">
                                                    <div className={avClass}>{initials}</div>
                                                    <div>
                                                        <h4>{ann.title}</h4>
                                                        <p>{ann.message?.slice(0, 100)}{ann.message?.length > 100 ? '…' : ''}</p>
                                                        <div className="db-when">{when} · {ann.created_by_name || ann.username || 'System'}</div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                ) : (
                                    <div className="db-empty-ann">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: 32, height: 32, opacity: 0.35 }}>
                                            <path d="M11 5L6 9H2v6h4l5 4V5zM19 12c0-2.5-1.5-5-4-6"/>
                                        </svg>
                                        Keine aktiven Ankündigungen
                                    </div>
                                )}
                                <Link to="/announcements" className="db-feat-cta">
                                    Alle Ankündigungen
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
                                </Link>
                            </div>

                            {/* Windows Agents */}
                            {monitoringStats && (
                                <Link to="/monitoring" style={{ textDecoration: 'none' }}>
                                    <div className="db-info-card">
                                        <div className="db-info-eyebrow">
                                            <span className="db-ico">
                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 5h8v8H3zM13 5h8v8h-8zM3 15h8v6H3zM13 15h8v6h-8z"/></svg>
                                            </span>
                                            Windows-Agents
                                        </div>
                                        <h3 className="db-info-title">
                                            {monitoringStats.offline === 0 ? 'Alle online.' : `${monitoringStats.offline} offline.`}
                                        </h3>
                                        <div className="db-agents-stat">
                                            <span className="num">{monitoringStats.online}</span>
                                            <span className="total">/ {monitoringStats.total}</span>
                                        </div>
                                        <div className="db-agents-bar">
                                            <span style={{ width: `${agentOnlinePct}%`, background: '#34c759' }} />
                                            <span style={{ width: `${100 - agentOnlinePct}%`, background: '#ef4444' }} />
                                        </div>
                                        <div className="db-agents-legend">
                                            <div><i style={{ background: '#34c759' }} />{monitoringStats.online} online</div>
                                            <div><i style={{ background: '#ef4444' }} />{monitoringStats.offline} offline</div>
                                            {monitoringStats.pendingUpdates > 0 && <div><i style={{ background: '#f59e0b' }} />{monitoringStats.pendingUpdates} Updates</div>}
                                        </div>
                                    </div>
                                </Link>
                            )}

                            {/* Patch Compliance Ring */}
                            {patchStats && (
                                <Link to="/patch-management" style={{ textDecoration: 'none' }}>
                                    <div className="db-info-card">
                                        <div className="db-info-eyebrow">
                                            <span className="db-ico">
                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v6M5 8l3 3M19 8l-3 3M3 14h18"/></svg>
                                            </span>
                                            Patch-Compliance
                                        </div>
                                        <h3 className="db-info-title">{patchPct} % konform.</h3>
                                        <div className="db-ring-wrap">
                                            <div className="db-ring">
                                                <svg viewBox="0 0 100 100">
                                                    <circle className="bg" cx="50" cy="50" r="42" fill="none" stroke="var(--border-color)" strokeWidth="10"/>
                                                    <circle className="fg" cx="50" cy="50" r="42" fill="none" stroke="var(--cereda-primary)" strokeWidth="10"
                                                        strokeDasharray={circumference.toFixed(1)} strokeDashoffset={dashoffset.toFixed(1)}
                                                        strokeLinecap="round"/>
                                                </svg>
                                                <div className="db-ring-pct">{patchPct}%</div>
                                            </div>
                                            <div className="db-ring-stats">
                                                <div><b>{patchStats.compliant || 0}</b> aktuell</div>
                                                <div><b>{patchStats.warnings || 0}</b> Warnungen</div>
                                                <div><b>{patchStats.offline || 0}</b> offline</div>
                                                {patchStats.total_pending_updates > 0 && <div><b>{patchStats.total_pending_updates}</b> Updates aust.</div>}
                                            </div>
                                        </div>
                                    </div>
                                </Link>
                            )}

                            {/* Security Report */}
                            {lastSecReport && (
                                <Link to="/security-reports" style={{ textDecoration: 'none' }}>
                                    <div className="db-info-card">
                                        <div className="db-info-eyebrow">
                                            <span className="db-ico">
                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                                            </span>
                                            Security-Report
                                        </div>
                                        <h3 className="db-info-title">{riskLabel}.</h3>
                                        <span className={`db-risk-badge-wrap ${riskClass}`}>
                                            <span className="db-rdot" />
                                            {lastSecReport.report_period || 'Letzter Report'} · {new Date(lastSecReport.created_at).toLocaleDateString('de-DE')}
                                        </span>
                                        {lastSecReport.analysis?.login_stats && (
                                            <div className="db-risk-stats">
                                                <div className="db-risk-stat">
                                                    <div className={`rv ${(lastSecReport.analysis.login_stats.failed || 0) > 500 ? 'red' : ''}`}>
                                                        {(lastSecReport.analysis.login_stats.failed || 0).toLocaleString('de-DE')}
                                                    </div>
                                                    <div className="rl">Login-Fehler</div>
                                                </div>
                                                <div className="db-risk-stat">
                                                    <div className="rv">{(lastSecReport.analysis.login_stats.success_rate || 0).toFixed(1)}%</div>
                                                    <div className="rl">Erfolgsrate</div>
                                                </div>
                                                {lastSecReport.analysis.non_european_logins?.length > 0 && (
                                                    <div className="db-risk-stat">
                                                        <div className="rv amber">{lastSecReport.analysis.non_european_logins.length}</div>
                                                        <div className="rl">Länder außerh. EU</div>
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                </Link>
                            )}

                            {/* Secure Share */}
                            {shareCount !== null && (
                                <a href="/share-tool.html" target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>
                                    <div className="db-info-card">
                                        <div className="db-info-eyebrow">
                                            <span className="db-ico">
                                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7.07 0l3-3a5 5 0 1 0-7.07-7.07L11 4.5M14 11a5 5 0 0 0-7.07 0l-3 3a5 5 0 0 0 7.07 7.07L13 19.5"/></svg>
                                            </span>
                                            Secure Share
                                        </div>
                                        <h3 className="db-info-title">Aktive Links.</h3>
                                        <div className="db-share-stat">{shareCount.active} <span>Links</span></div>
                                        <div className="db-share-list">
                                            <div><span className="db-sdot" style={{ background: '#34c759' }} />{shareCount.active} aktiv</div>
                                            {shareCount.expiringSoon > 0 && <div><span className="db-sdot" style={{ background: '#f59e0b' }} />{shareCount.expiringSoon} ablaufend ≤ 7 T</div>}
                                            <div><span className="db-sdot" style={{ background: 'var(--text-muted)' }} />{shareCount.total - shareCount.active} abgelaufen</div>
                                        </div>
                                    </div>
                                </a>
                            )}

                        </div>
                    </div>
                )}

                {/* ═══ HELPDESK METRIKEN ═══ */}
                {ticketMetrics && (
                    <div className="db-block">
                        <div className="db-section-head">
                            <div>
                                <h2>Helpdesk-Leistung.</h2>
                                <p>Lösungszeiten nach Priorität und Top-Bearbeiter.</p>
                            </div>
                        </div>
                        <div className="db-two-col">
                            <div className="db-card">
                                <div className="db-card-head">
                                    <h3 className="db-card-title">Ø Lösungszeit</h3>
                                    <p className="db-card-sub">Letzte 30 Tage · alle Tickets</p>
                                </div>
                                <div className="db-metrics-grid">
                                    {(ticketMetrics.avgResolution || []).slice(0, 3).map((r, i) => {
                                        const cls = ['m-hi', 'm-mid', 'm-low'][i] || 'm-low';
                                        const val = r.avg_hours < 1 ? '<1' : r.avg_hours < 24 ? r.avg_hours : Math.round(r.avg_hours / 24);
                                        const unit = r.avg_hours < 24 ? 'h' : 'T';
                                        return (
                                            <div key={r.priority} className={`db-metric ${cls}`}>
                                                <div className="db-metric-prio">
                                                    <span className="db-mp" />
                                                    {r.priority}
                                                </div>
                                                <div className="db-metric-value">{val}<span className="u">{unit}</span></div>
                                                <div className="db-metric-label">Ø Lösungszeit</div>
                                            </div>
                                        );
                                    })}
                                    {ticketMetrics.slaBreaches?.length > 0 && (
                                        <div className="db-metric m-sla">
                                            <div className="db-metric-prio">
                                                <span className="db-mp" />
                                                SLA
                                            </div>
                                            <div className="db-metric-value">{ticketMetrics.slaBreaches.reduce((s, b) => s + b.count, 0)}</div>
                                            <div className="db-metric-label">Verletzungen offen</div>
                                        </div>
                                    )}
                                </div>
                            </div>
                            {ticketMetrics.topAssignees?.length > 0 && (
                                <div className="db-card">
                                    <div className="db-card-head">
                                        <h3 className="db-card-title">Top-Bearbeiter</h3>
                                        <p className="db-card-sub">Gelöste Tickets · 30 Tage</p>
                                    </div>
                                    {ticketMetrics.topAssignees.slice(0, 4).map((a, i) => {
                                        const initial = (a.first_name?.[0] || a.username[0]).toUpperCase();
                                        const rankCls = i === 0 ? 'gold' : i === 1 ? 'silver' : '';
                                        return (
                                            <div key={a.username} className="db-performer">
                                                <div className="db-perf-av" style={{ background: getAvatarColor(a.username) }}>{initial}</div>
                                                <div>
                                                    <div className="db-perf-name">{a.first_name || a.username}</div>
                                                    <div className="db-perf-stats">{a.closed} Tickets gelöst · {a.total} gesamt</div>
                                                </div>
                                                <div className={`db-perf-rank ${rankCls}`}>#{i + 1}</div>
                                            </div>
                                        );
                                    })}
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {/* ═══ LETZTE AKTIVITÄTEN ═══ */}
                {isAdmin() && recentLogs.length > 0 && (
                    <div className="db-block" style={{ marginBottom: 0 }}>
                        <div className="db-section-head">
                            <div>
                                <h2>Letzte Aktivitäten.</h2>
                                <p>Alle Schreibvorgänge im Audit-Log.</p>
                            </div>
                        </div>
                        <div className="db-table-card">
                            <div className="db-table-head">
                                <div className="db-filter-pills">
                                    {['Alle', 'Assets', 'Benutzer', 'Onboarding', 'Tickets'].map(f => (
                                        <button key={f} className={logFilter === f ? 'on' : ''} onClick={() => setLogFilter(f)}>{f}</button>
                                    ))}
                                </div>
                            </div>
                            <table className="db-table">
                                <thead>
                                    <tr>
                                        <th style={{ width: 220 }}>Benutzer</th>
                                        <th style={{ width: 240 }}>Aktion</th>
                                        <th>Typ</th>
                                        <th style={{ width: 160 }}>Zeitpunkt</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {filteredLogs.map(log => (
                                        <tr key={log.id}>
                                            <td>
                                                <div className="db-user-cell">
                                                    <div className="db-av-sm" style={{ background: getAvatarColor(log.username) }}>
                                                        {(log.username || '?')[0].toUpperCase()}
                                                    </div>
                                                    <span>{log.username}</span>
                                                </div>
                                            </td>
                                            <td>
                                                <span className={`db-action-pill ${actionPillClass(log.action)}`}>
                                                    {actionPillLabel(log.action)}
                                                </span>
                                            </td>
                                            <td><span className="db-type-pill">{log.entity_type}</span></td>
                                            <td className="db-time-cell">{new Date(log.created_at).toLocaleString('de-DE', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

            </div>
        </div>
    );
};

export default DashboardPage;
