import React, { useState, useEffect, useCallback, useRef } from 'react';
import networkMonitorService from '../services/networkMonitorService';
import { toast } from 'react-toastify';

// ─── Constants ────────────────────────────────────────────────────────────────
const TYPE_META = {
    host:    { label: 'Host',     icon: '🖥' },
    switch:  { label: 'Switch',   icon: '🔀' },
    router:  { label: 'Router',   icon: '🌐' },
    printer: { label: 'Drucker',  icon: '🖨' },
    nas:     { label: 'NAS',      icon: '💾' },
    service: { label: 'Service',  icon: '⚙' },
};

const CHECK_TYPES = ['icmp', 'http', 'https', 'tcp'];
const INTERVALS = [
    { value: 15,  label: '15 Sek' },
    { value: 30,  label: '30 Sek' },
    { value: 60,  label: '1 Min' },
    { value: 300, label: '5 Min' },
    { value: 600, label: '10 Min' },
];

// ─── Helpers ─────────────────────────────────────────────────────────────────
const timeAgo = (iso) => {
    if (!iso) return '–';
    const m = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
    if (m < 1) return 'gerade eben';
    if (m < 60) return `vor ${m} Min`;
    if (m < 1440) return `vor ${Math.floor(m / 60)} Std`;
    return `vor ${Math.floor(m / 1440)} Tagen`;
};

const statusColor = (s) => s === 'up' ? '#34d399' : s === 'down' ? '#ef4444' : '#6b7280';
const statusLabel = (s) => s === 'up' ? 'Online' : s === 'down' ? 'Offline' : 'Unbekannt';

// ─── Uptime Sparkline ─────────────────────────────────────────────────────────
const UptimeSparkline = ({ checks }) => {
    if (!checks || checks.length === 0) return <div style={{ color: 'var(--text-muted)', fontSize: 11 }}>Keine Daten</div>;
    const seg = checks.slice(-80);
    const w = 240, h = 28, sw = w / seg.length;
    return (
        <svg width={w} height={h} style={{ borderRadius: 4, overflow: 'hidden' }}>
            {seg.map((c, i) => (
                <rect key={i} x={i * sw} y={0} width={Math.max(sw - 0.5, 1)} height={h}
                    fill={c.status === 'up' ? '#34d399' : '#ef4444'} opacity={0.85} />
            ))}
        </svg>
    );
};

// ─── RTT Sparkline ────────────────────────────────────────────────────────────
const RttSparkline = ({ checks }) => {
    const vals = checks.filter(c => c.rtt_ms != null).map(c => c.rtt_ms);
    if (vals.length < 2) return <div style={{ color: 'var(--text-muted)', fontSize: 11 }}>–</div>;
    const max = Math.max(...vals);
    const w = 240, h = 40;
    const points = vals.slice(-60).map((v, i) => {
        const x = (i / (vals.slice(-60).length - 1)) * w;
        const y = h - (v / max) * (h - 4) - 2;
        return `${x},${y}`;
    }).join(' ');
    return (
        <svg width={w} height={h}>
            <polyline points={points} fill="none" stroke="var(--accent)" strokeWidth="1.5" />
        </svg>
    );
};

// ─── Status Dot ───────────────────────────────────────────────────────────────
const StatusDot = ({ status, size = 10 }) => (
    <span style={{
        display: 'inline-block', width: size, height: size, borderRadius: '50%',
        background: statusColor(status),
        boxShadow: status === 'up' ? `0 0 6px ${statusColor(status)}` : 'none',
        animation: status === 'up' ? 'nmPulse 2s infinite' : 'none',
        flexShrink: 0,
    }} />
);

// ─── Device Card ─────────────────────────────────────────────────────────────
const DeviceCard = ({ device, onClick }) => {
    const meta = TYPE_META[device.type] || TYPE_META.host;
    const borderColor = statusColor(device.last_status);
    return (
        <div onClick={onClick} style={{
            background: 'var(--bg-secondary)', border: `1px solid var(--border-color)`,
            borderTop: `3px solid ${borderColor}`, borderRadius: 10, padding: '14px 16px',
            cursor: 'pointer', transition: 'transform .15s, box-shadow .15s',
        }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 6px 20px rgba(0,0,0,.3)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}
        >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontSize: 20 }}>{meta.icon}</span>
                    <div>
                        <div style={{ fontWeight: 700, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 160 }}>{device.name}</div>
                        <div style={{ color: 'var(--text-muted)', fontSize: 11 }}>{device.host}</div>
                    </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '3px 8px', borderRadius: 12, fontSize: 11, fontWeight: 600,
                    background: `${statusColor(device.last_status)}20`, color: statusColor(device.last_status), border: `1px solid ${statusColor(device.last_status)}40` }}>
                    <StatusDot status={device.last_status} size={7} />
                    {statusLabel(device.last_status)}
                </div>
            </div>

            {device.location && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 6 }}>📍 {device.location}</div>}

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, color: 'var(--text-muted)', marginTop: 8 }}>
                <span>{device.check_type?.toUpperCase()} · {TYPE_META[device.type]?.label}</span>
                <span>{device.last_rtt_ms != null ? `${Math.round(device.last_rtt_ms)} ms` : '–'}</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4 }}>{timeAgo(device.last_checked)}</div>
        </div>
    );
};

// ─── Discovery Modal ──────────────────────────────────────────────────────────
const TYPE_META_DISCOVER = { ...TYPE_META };

const DiscoverModal = ({ onClose, onAdd }) => {
    const [subnet, setSubnet] = useState('192.168.0');
    const [scanning, setScanning] = useState(false);
    const [progress, setProgress] = useState(0);
    const [results, setResults] = useState(null);
    const [selected, setSelected] = useState({});
    const [typeOverrides, setTypeOverrides] = useState({});
    const [adding, setAdding] = useState(false);
    const progressRef = useRef(null);

    const startScan = async () => {
        setScanning(true);
        setResults(null);
        setSelected({});
        setProgress(0);

        // Animate progress bar during scan
        let p = 0;
        progressRef.current = setInterval(() => {
            p = Math.min(p + 1.2, 90);
            setProgress(p);
        }, 500);

        try {
            const res = await networkMonitorService.discover(subnet);
            clearInterval(progressRef.current);
            setProgress(100);
            setResults(res.data || []);
            // Auto-select all found
            const sel = {};
            (res.data || []).forEach(d => sel[d.ip] = true);
            setSelected(sel);
        } catch {
            clearInterval(progressRef.current);
            toast.error('Scan fehlgeschlagen');
        } finally {
            setScanning(false);
        }
    };

    const addSelected = async () => {
        const toAdd = (results || []).filter(d => selected[d.ip]);
        if (!toAdd.length) return;
        setAdding(true);
        let added = 0;
        for (const d of toAdd) {
            try {
                const type = typeOverrides[d.ip] || d.type;
                const device = await networkMonitorService.create({
                    name: d.hostname || d.ip,
                    type,
                    host: d.ip,
                    check_type: d.check_type,
                    interval_sec: 60,
                    timeout_sec: 5,
                    enabled: 1,
                });
                onAdd(device);
                added++;
            } catch {}
        }
        toast.success(`${added} Gerät${added !== 1 ? 'e' : ''} hinzugefügt`);
        setAdding(false);
        onClose();
    };

    const toggleAll = (val) => {
        const sel = {};
        (results || []).forEach(d => sel[d.ip] = val);
        setSelected(sel);
    };

    const inputStyle = { padding: '8px 12px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: 13 };

    return (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.65)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
            onClick={e => e.target === e.currentTarget && !scanning && onClose()}>
            <div style={{ background: 'var(--bg-primary)', borderRadius: 12, width: '100%', maxWidth: 600, maxHeight: '90vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', border: '1px solid var(--border-color)' }}>
                {/* Header */}
                <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-color)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <h2 style={{ fontSize: 16, fontWeight: 700 }}>📡 Netzwerk scannen</h2>
                    {!scanning && <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: 22, cursor: 'pointer' }}>×</button>}
                </div>

                <div style={{ padding: 20, overflowY: 'auto', flex: 1 }}>
                    {/* Subnet input */}
                    <div style={{ display: 'flex', gap: 10, marginBottom: 16, alignItems: 'flex-end' }}>
                        <div style={{ flex: 1 }}>
                            <label style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.4px', display: 'block', marginBottom: 6 }}>Subnetz (erste 3 Oktette)</label>
                            <input style={{ ...inputStyle, width: '100%', boxSizing: 'border-box' }}
                                value={subnet} onChange={e => setSubnet(e.target.value)}
                                placeholder="192.168.0" disabled={scanning} />
                        </div>
                        <button onClick={startScan} disabled={scanning || !subnet}
                            style={{ padding: '9px 20px', borderRadius: 7, border: 'none', background: 'var(--accent)', color: '#fff', cursor: scanning ? 'not-allowed' : 'pointer', fontWeight: 700, fontSize: 13, whiteSpace: 'nowrap' }}>
                            {scanning ? 'Scanne...' : '▶ Scan starten'}
                        </button>
                    </div>

                    {/* Progress */}
                    {(scanning || results !== null) && (
                        <div style={{ marginBottom: 16 }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-muted)', marginBottom: 6 }}>
                                <span>{scanning ? `Scanne ${subnet}.1 – ${subnet}.254...` : `Scan abgeschlossen – ${results?.length || 0} Geräte gefunden`}</span>
                                <span>{Math.round(progress)}%</span>
                            </div>
                            <div style={{ background: 'var(--border-color)', borderRadius: 4, height: 6, overflow: 'hidden' }}>
                                <div style={{ height: '100%', width: `${progress}%`, background: progress === 100 ? '#34d399' : 'var(--accent)', borderRadius: 4, transition: 'width .4s' }} />
                            </div>
                        </div>
                    )}

                    {/* Results */}
                    {results !== null && results.length === 0 && (
                        <div style={{ textAlign: 'center', color: 'var(--text-muted)', padding: 30, fontSize: 14 }}>
                            Keine neuen Geräte gefunden im Subnetz {subnet}.x
                        </div>
                    )}

                    {results && results.length > 0 && (
                        <>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                                <span style={{ fontSize: 13, fontWeight: 600 }}>{Object.values(selected).filter(Boolean).length} von {results.length} ausgewählt</span>
                                <div style={{ display: 'flex', gap: 8 }}>
                                    <button onClick={() => toggleAll(true)} style={{ fontSize: 11, padding: '3px 10px', borderRadius: 5, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>Alle</button>
                                    <button onClick={() => toggleAll(false)} style={{ fontSize: 11, padding: '3px 10px', borderRadius: 5, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>Keine</button>
                                </div>
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                                {results.map(d => (
                                    <div key={d.ip} onClick={() => setSelected(s => ({ ...s, [d.ip]: !s[d.ip] }))}
                                        style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 8,
                                            background: selected[d.ip] ? 'rgba(63,163,163,.12)' : 'var(--bg-secondary)',
                                            border: `1px solid ${selected[d.ip] ? 'var(--accent)' : 'var(--border-color)'}`,
                                            cursor: 'pointer', transition: 'all .1s' }}>
                                        <input type="checkbox" checked={!!selected[d.ip]} onChange={() => {}} style={{ accentColor: 'var(--accent)' }} />
                                        <span style={{ fontSize: 18 }}>{TYPE_META[typeOverrides[d.ip] || d.type]?.icon || '🖥'}</span>
                                        <div style={{ flex: 1, minWidth: 0 }}>
                                            <div style={{ fontWeight: 600, fontSize: 13 }}>{d.ip}</div>
                                            {d.hostname && <div style={{ fontSize: 11, color: 'var(--text-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.hostname}</div>}
                                            {d.open_ports?.length > 0 && <div style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 2 }}>Ports: {d.open_ports.join(', ')}</div>}
                                        </div>
                                        <select value={typeOverrides[d.ip] || d.type}
                                            onChange={e => { e.stopPropagation(); setTypeOverrides(t => ({ ...t, [d.ip]: e.target.value })); }}
                                            onClick={e => e.stopPropagation()}
                                            style={{ fontSize: 11, padding: '3px 6px', borderRadius: 5, border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'var(--text-primary)', cursor: 'pointer' }}>
                                            {Object.entries(TYPE_META).map(([k, v]) => <option key={k} value={k}>{v.icon} {v.label}</option>)}
                                        </select>
                                        <span style={{ fontSize: 11, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{d.check_type.toUpperCase()}</span>
                                    </div>
                                ))}
                            </div>
                        </>
                    )}
                </div>

                {/* Footer */}
                {results && results.length > 0 && (
                    <div style={{ padding: '14px 20px', borderTop: '1px solid var(--border-color)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
                        <button onClick={onClose} disabled={adding} style={{ padding: '8px 16px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-primary)', cursor: 'pointer', fontSize: 13 }}>Abbrechen</button>
                        <button onClick={addSelected} disabled={adding || !Object.values(selected).some(Boolean)}
                            style={{ padding: '8px 18px', borderRadius: 7, border: 'none', background: 'var(--accent)', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: 13 }}>
                            {adding ? 'Füge hinzu...' : `${Object.values(selected).filter(Boolean).length} Gerät${Object.values(selected).filter(Boolean).length !== 1 ? 'e' : ''} hinzufügen`}
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
};

// ─── Device Form Modal ────────────────────────────────────────────────────────
const DeviceFormModal = ({ device, onSave, onClose }) => {
    const [form, setForm] = useState({
        name: '', type: 'host', host: '', check_type: 'icmp',
        port: '', http_path: '/', http_keyword: '', interval_sec: 60,
        timeout_sec: 5, enabled: 1, notify_email: '', location: '',
        ...(device || {}),
    });
    const [saving, setSaving] = useState(false);
    const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

    const save = async () => {
        if (!form.name || !form.host) return toast.error('Name und Host sind Pflichtfelder');
        setSaving(true);
        try {
            const result = device
                ? await networkMonitorService.update(device.id, form)
                : await networkMonitorService.create(form);
            onSave(result);
            onClose();
            toast.success(device ? 'Gerät aktualisiert' : 'Gerät hinzugefügt');
        } catch { toast.error('Fehler beim Speichern'); }
        finally { setSaving(false); }
    };

    const inputStyle = { width: '100%', padding: '8px 10px', borderRadius: 6, border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'var(--text-primary)', fontSize: 13, boxSizing: 'border-box' };
    const labelStyle = { fontSize: 12, color: 'var(--text-muted)', fontWeight: 600, marginBottom: 4, display: 'block', textTransform: 'uppercase', letterSpacing: '.4px' };

    return (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.6)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && onClose()}>
            <div style={{ background: 'var(--bg-primary)', borderRadius: 12, width: '100%', maxWidth: 540, maxHeight: '90vh', overflow: 'auto', border: '1px solid var(--border-color)' }}>
                <div style={{ padding: '18px 20px', borderBottom: '1px solid var(--border-color)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <h2 style={{ fontSize: 16, fontWeight: 700 }}>{device ? 'Gerät bearbeiten' : 'Neues Gerät'}</h2>
                    <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: 20, cursor: 'pointer' }}>×</button>
                </div>
                <div style={{ padding: 20, display: 'grid', gap: 14 }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                        <div>
                            <label style={labelStyle}>Name *</label>
                            <input style={inputStyle} value={form.name} onChange={e => set('name', e.target.value)} placeholder="z.B. Core Switch" />
                        </div>
                        <div>
                            <label style={labelStyle}>Typ</label>
                            <select style={inputStyle} value={form.type} onChange={e => set('type', e.target.value)}>
                                {Object.entries(TYPE_META).map(([k, v]) => <option key={k} value={k}>{v.icon} {v.label}</option>)}
                            </select>
                        </div>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                        <div>
                            <label style={labelStyle}>Host / IP *</label>
                            <input style={inputStyle} value={form.host} onChange={e => set('host', e.target.value)} placeholder="192.168.0.1" />
                        </div>
                        <div>
                            <label style={labelStyle}>Standort</label>
                            <input style={inputStyle} value={form.location || ''} onChange={e => set('location', e.target.value)} placeholder="z.B. Serverraum" />
                        </div>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                        <div>
                            <label style={labelStyle}>Check-Typ</label>
                            <select style={inputStyle} value={form.check_type} onChange={e => set('check_type', e.target.value)}>
                                {CHECK_TYPES.map(t => <option key={t} value={t}>{t.toUpperCase()}</option>)}
                            </select>
                        </div>
                        {(form.check_type === 'tcp' || form.check_type === 'http' || form.check_type === 'https') && (
                            <div>
                                <label style={labelStyle}>Port {form.check_type === 'tcp' ? '*' : '(optional)'}</label>
                                <input style={inputStyle} type="number" value={form.port || ''} onChange={e => set('port', e.target.value)} placeholder={form.check_type === 'https' ? '443' : form.check_type === 'http' ? '80' : ''} />
                            </div>
                        )}
                        <div>
                            <label style={labelStyle}>Intervall</label>
                            <select style={inputStyle} value={form.interval_sec} onChange={e => set('interval_sec', parseInt(e.target.value))}>
                                {INTERVALS.map(i => <option key={i.value} value={i.value}>{i.label}</option>)}
                            </select>
                        </div>
                    </div>
                    {(form.check_type === 'http' || form.check_type === 'https') && (
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                            <div>
                                <label style={labelStyle}>Pfad</label>
                                <input style={inputStyle} value={form.http_path || '/'} onChange={e => set('http_path', e.target.value)} placeholder="/" />
                            </div>
                            <div>
                                <label style={labelStyle}>Keyword (optional)</label>
                                <input style={inputStyle} value={form.http_keyword || ''} onChange={e => set('http_keyword', e.target.value)} placeholder="Erwarteter Text in Response" />
                            </div>
                        </div>
                    )}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                        <div>
                            <label style={labelStyle}>Timeout (Sek)</label>
                            <input style={inputStyle} type="number" min="1" max="30" value={form.timeout_sec} onChange={e => set('timeout_sec', parseInt(e.target.value))} />
                        </div>
                        <div>
                            <label style={labelStyle}>Alert E-Mail</label>
                            <input style={inputStyle} value={form.notify_email || ''} onChange={e => set('notify_email', e.target.value)} placeholder="admin@firma.de" />
                        </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <input type="checkbox" id="enabled" checked={!!form.enabled} onChange={e => set('enabled', e.target.checked ? 1 : 0)} />
                        <label htmlFor="enabled" style={{ fontSize: 13, cursor: 'pointer' }}>Monitoring aktiv</label>
                    </div>
                </div>
                <div style={{ padding: '14px 20px', borderTop: '1px solid var(--border-color)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
                    <button onClick={onClose} style={{ padding: '8px 18px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-primary)', cursor: 'pointer', fontSize: 13 }}>Abbrechen</button>
                    <button onClick={save} disabled={saving} style={{ padding: '8px 18px', borderRadius: 7, border: 'none', background: 'var(--accent)', color: '#fff', cursor: 'pointer', fontSize: 13, fontWeight: 600 }}>
                        {saving ? 'Speichere...' : 'Speichern'}
                    </button>
                </div>
            </div>
        </div>
    );
};

// ─── Detail Modal ─────────────────────────────────────────────────────────────
const DetailModal = ({ device, onClose, onEdit, onDelete, onCheckNow }) => {
    const [checksData, setChecksData] = useState(null);
    const [timeRange, setTimeRange] = useState(24);
    const [checking, setChecking] = useState(false);

    useEffect(() => {
        networkMonitorService.getChecks(device.id, timeRange)
            .then(setChecksData).catch(() => {});
    }, [device.id, timeRange]);

    const doCheckNow = async () => {
        setChecking(true);
        try {
            await onCheckNow(device.id);
            toast.success('Check ausgeführt');
            const data = await networkMonitorService.getChecks(device.id, timeRange);
            setChecksData(data);
        } catch { toast.error('Check fehlgeschlagen'); }
        finally { setChecking(false); }
    };

    const meta = TYPE_META[device.type] || TYPE_META.host;
    const uptime = checksData?.uptime;
    const checks = checksData?.checks || [];
    const lastChecks = [...checks].reverse().slice(0, 20);

    return (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.6)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && onClose()}>
            <div style={{ background: 'var(--bg-primary)', borderRadius: 12, width: '100%', maxWidth: 660, maxHeight: '90vh', overflow: 'auto', border: `1px solid var(--border-color)`, borderTop: `3px solid ${statusColor(device.last_status)}` }}>
                {/* Header */}
                <div style={{ padding: '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid var(--border-color)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <span style={{ fontSize: 24 }}>{meta.icon}</span>
                        <div>
                            <div style={{ fontWeight: 700, fontSize: 16 }}>{device.name}</div>
                            <div style={{ color: 'var(--text-muted)', fontSize: 12 }}>{device.host} · {meta.label}</div>
                        </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 12, fontSize: 12, fontWeight: 600,
                            background: `${statusColor(device.last_status)}20`, color: statusColor(device.last_status) }}>
                            <StatusDot status={device.last_status} size={8} />
                            {statusLabel(device.last_status)}
                        </div>
                        <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: 22, cursor: 'pointer' }}>×</button>
                    </div>
                </div>

                <div style={{ padding: 20 }}>
                    {/* Stats row */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 20 }}>
                        {[
                            { label: 'Letzter Check', value: timeAgo(device.last_checked) },
                            { label: 'Antwortzeit', value: device.last_rtt_ms != null ? `${Math.round(device.last_rtt_ms)} ms` : '–' },
                            { label: `Uptime ${timeRange}h`, value: uptime?.total > 0 ? `${uptime.pct}%` : '–', color: uptime?.pct >= 99 ? '#34d399' : uptime?.pct >= 90 ? '#f59e0b' : '#ef4444' },
                        ].map(m => (
                            <div key={m.label} style={{ background: 'var(--bg-secondary)', borderRadius: 8, padding: '10px 14px' }}>
                                <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.4px', marginBottom: 4 }}>{m.label}</div>
                                <div style={{ fontSize: 18, fontWeight: 700, color: m.color || 'var(--text-primary)' }}>{m.value}</div>
                            </div>
                        ))}
                    </div>

                    {/* Time range + Uptime graph */}
                    <div style={{ marginBottom: 16 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.4px' }}>Uptime-Verlauf</div>
                            <div style={{ display: 'flex', gap: 4 }}>
                                {[24, 48, 168].map(h => (
                                    <button key={h} onClick={() => setTimeRange(h)} style={{
                                        padding: '3px 10px', borderRadius: 5, fontSize: 11, fontWeight: 600, cursor: 'pointer',
                                        border: `1px solid ${timeRange === h ? 'var(--accent)' : 'var(--border-color)'}`,
                                        background: timeRange === h ? 'var(--accent)' : 'var(--bg-secondary)',
                                        color: timeRange === h ? '#fff' : 'var(--text-muted)',
                                    }}>{h === 168 ? '7 Tage' : `${h}h`}</button>
                                ))}
                            </div>
                        </div>
                        <div style={{ background: 'var(--bg-secondary)', borderRadius: 8, padding: 10 }}>
                            <UptimeSparkline checks={checks} />
                            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-muted)', marginTop: 4 }}>
                                <span>↑ Grün = Online &nbsp; Rot = Offline</span>
                                <span>{uptime?.up ?? 0}/{uptime?.total ?? 0} Checks OK</span>
                            </div>
                        </div>
                    </div>

                    {/* RTT Graph */}
                    {checks.some(c => c.rtt_ms != null) && (
                        <div style={{ marginBottom: 16 }}>
                            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.4px', marginBottom: 8 }}>Antwortzeit (ms)</div>
                            <div style={{ background: 'var(--bg-secondary)', borderRadius: 8, padding: 10 }}>
                                <RttSparkline checks={checks} />
                            </div>
                        </div>
                    )}

                    {/* Info Grid */}
                    <div style={{ background: 'var(--bg-secondary)', borderRadius: 8, padding: '12px 14px', marginBottom: 16 }}>
                        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.4px', marginBottom: 8 }}>Konfiguration</div>
                        <div style={{ display: 'grid', gridTemplateColumns: '130px 1fr', gap: '5px 12px', fontSize: 13, lineHeight: 1.7 }}>
                            {[
                                ['Check-Typ', device.check_type?.toUpperCase()],
                                ['Intervall', `${device.interval_sec}s`],
                                ['Timeout', `${device.timeout_sec}s`],
                                device.port && ['Port', device.port],
                                device.location && ['Standort', device.location],
                                device.notify_email && ['Alert E-Mail', device.notify_email],
                            ].filter(Boolean).map(([k, v]) => (
                                <React.Fragment key={k}>
                                    <span style={{ color: 'var(--text-muted)' }}>{k}</span>
                                    <span style={{ fontWeight: 600 }}>{v}</span>
                                </React.Fragment>
                            ))}
                        </div>
                    </div>

                    {/* Check History */}
                    {lastChecks.length > 0 && (
                        <div>
                            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '.4px', marginBottom: 8 }}>Letzte Checks</div>
                            <div style={{ maxHeight: 180, overflowY: 'auto' }}>
                                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                                    <tbody>
                                        {lastChecks.map((c, i) => (
                                            <tr key={i} style={{ borderBottom: '1px solid var(--border-color)' }}>
                                                <td style={{ padding: '5px 0', width: 16 }}><StatusDot status={c.status} size={8} /></td>
                                                <td style={{ padding: '5px 8px', color: c.status === 'up' ? '#34d399' : '#ef4444', fontWeight: 600 }}>{c.status === 'up' ? 'Online' : 'Offline'}</td>
                                                <td style={{ padding: '5px 8px', color: 'var(--text-muted)' }}>{c.rtt_ms != null ? `${Math.round(c.rtt_ms)} ms` : '–'}</td>
                                                <td style={{ padding: '5px 0', color: 'var(--text-muted)', textAlign: 'right' }}>{new Date(c.checked_at).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}</td>
                                                {c.error_msg && <td style={{ padding: '5px 8px', color: '#ef4444', fontSize: 11 }}>{c.error_msg}</td>}
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div style={{ padding: '14px 20px', borderTop: '1px solid var(--border-color)', display: 'flex', gap: 8 }}>
                    <button onClick={doCheckNow} disabled={checking} style={{ padding: '7px 14px', borderRadius: 7, border: '1px solid var(--accent)', background: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 13, fontWeight: 600 }}>
                        {checking ? '...' : '▶ Jetzt prüfen'}
                    </button>
                    <button onClick={() => { onEdit(device); onClose(); }} style={{ padding: '7px 14px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-primary)', cursor: 'pointer', fontSize: 13 }}>Bearbeiten</button>
                    <div style={{ flex: 1 }} />
                    <button onClick={() => onDelete(device)} style={{ padding: '7px 14px', borderRadius: 7, border: '1px solid #ef4444', background: 'none', color: '#ef4444', cursor: 'pointer', fontSize: 13 }}>Löschen</button>
                </div>
            </div>
        </div>
    );
};

// ─── Main Page ────────────────────────────────────────────────────────────────
export default function NetworkMonitorPage() {
    const [devices, setDevices] = useState([]);
    const [stats, setStats] = useState(null);
    const [search, setSearch] = useState('');
    const [filterType, setFilterType] = useState('all');
    const [filterStatus, setFilterStatus] = useState('all');
    const [selected, setSelected] = useState(null);
    const [editDevice, setEditDevice] = useState(null);
    const [showForm, setShowForm] = useState(false);
    const [showDiscover, setShowDiscover] = useState(false);
    const [loading, setLoading] = useState(true);
    const esRef = useRef(null);

    const loadStats = useCallback(() => {
        networkMonitorService.getStats().then(setStats).catch(() => {});
    }, []);

    // SSE connection with polling fallback
    useEffect(() => {
        let pollTimer = null;
        let sseConnected = false;

        const loadViaApi = () => {
            networkMonitorService.getAll()
                .then(d => { setDevices(d); setLoading(false); })
                .catch(() => setLoading(false));
        };

        const startPolling = () => {
            if (pollTimer) return;
            loadViaApi();
            pollTimer = setInterval(loadViaApi, 15000);
        };

        let es;
        try {
            es = networkMonitorService.createSSE();
            esRef.current = es;

            // If SSE doesn't connect within 4s, fall back to polling
            const sseTimeout = setTimeout(() => {
                if (!sseConnected) { es.close(); startPolling(); }
            }, 4000);

            es.addEventListener('initial_state', e => {
                sseConnected = true;
                clearTimeout(sseTimeout);
                setDevices(JSON.parse(e.data));
                setLoading(false);
            });
            es.addEventListener('device_update', e => {
                const updated = JSON.parse(e.data);
                setDevices(prev => {
                    const exists = prev.find(d => d.id === updated.id);
                    return exists ? prev.map(d => d.id === updated.id ? updated : d) : [...prev, updated];
                });
                setSelected(prev => prev?.id === updated.id ? updated : prev);
            });
            es.addEventListener('device_deleted', e => {
                const { id } = JSON.parse(e.data);
                setDevices(prev => prev.filter(d => d.id !== id));
            });
            es.onerror = () => {
                clearTimeout(sseTimeout);
                if (!sseConnected) { es.close(); startPolling(); }
            };
        } catch {
            startPolling();
        }

        loadStats();
        return () => {
            es?.close();
            if (pollTimer) clearInterval(pollTimer);
        };
    }, [loadStats]);

    // Refresh stats when devices change
    useEffect(() => { loadStats(); }, [devices.length, loadStats]);

    const filtered = devices.filter(d => {
        if (filterStatus !== 'all' && d.last_status !== filterStatus) return false;
        if (filterType !== 'all' && d.type !== filterType) return false;
        if (search) {
            const s = search.toLowerCase();
            return d.name.toLowerCase().includes(s) || d.host.toLowerCase().includes(s) || (d.location || '').toLowerCase().includes(s);
        }
        return true;
    });

    const handleDelete = async (device) => {
        if (!window.confirm(`${device.name} wirklich löschen?`)) return;
        try {
            await networkMonitorService.delete(device.id);
            setSelected(null);
            toast.success('Gerät gelöscht');
        } catch { toast.error('Fehler beim Löschen'); }
    };

    const handleSave = (device) => {
        setDevices(prev => {
            const exists = prev.find(d => d.id === device.id);
            return exists ? prev.map(d => d.id === device.id ? device : d) : [...prev, device];
        });
    };

    const onlineCount = devices.filter(d => d.last_status === 'up').length;
    const offlineCount = devices.filter(d => d.last_status === 'down').length;

    if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>Verbinde mit Monitoring-Service...</div>;

    return (
        <div style={{ padding: 24 }}>
            <style>{`
                @keyframes nmPulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:.5;transform:scale(1.3)} }
                ::-webkit-scrollbar { width: 6px; height: 6px; }
                ::-webkit-scrollbar-track { background: transparent; }
                ::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.12); border-radius: 10px; }
                ::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.22); }
            `}</style>

            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
                <div>
                    <h1 style={{ fontSize: 22, fontWeight: 700, marginBottom: 4 }}>Netzwerk Monitoring</h1>
                    <p style={{ color: 'var(--text-muted)', fontSize: 13 }}>Echtzeit-Überwachung aller Netzwerkgeräte</p>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                    <button onClick={() => setShowDiscover(true)} style={{
                        padding: '9px 16px', borderRadius: 8, border: '1px solid var(--border-color)',
                        background: 'var(--bg-secondary)', color: 'var(--text-primary)', cursor: 'pointer', fontSize: 13, fontWeight: 600,
                    }}>📡 Auto-Discovery</button>
                    <button onClick={() => { setEditDevice(null); setShowForm(true); }} style={{
                        padding: '9px 18px', borderRadius: 8, border: 'none', background: 'var(--accent)',
                        color: '#fff', cursor: 'pointer', fontSize: 13, fontWeight: 600,
                    }}>+ Manuell hinzufügen</button>
                </div>
            </div>

            {/* Stats */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))', gap: 12, marginBottom: 24 }}>
                {[
                    { label: 'Gesamt', value: devices.length, color: 'var(--accent)', border: 'var(--accent)' },
                    { label: 'Online', value: onlineCount, color: '#34d399', border: '#34d399', sub: devices.length > 0 ? `${Math.round(onlineCount / devices.length * 100)}%` : '' },
                    { label: 'Offline', value: offlineCount, color: offlineCount > 0 ? '#ef4444' : 'var(--text-muted)', border: offlineCount > 0 ? '#ef4444' : 'var(--border-color)' },
                    { label: 'Unbekannt', value: devices.filter(d => d.last_status === 'unknown').length, color: 'var(--text-muted)', border: 'var(--border-color)' },
                ].map(s => (
                    <div key={s.label} className="card" style={{ padding: '14px 16px', borderLeft: `3px solid ${s.border}` }}>
                        <div style={{ fontSize: 24, fontWeight: 800, color: s.color }}>{s.value}</div>
                        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>{s.label}</div>
                        {s.sub && <div style={{ fontSize: 11, color: s.color, marginTop: 2 }}>{s.sub} verfügbar</div>}
                    </div>
                ))}
            </div>

            {/* Toolbar */}
            <div style={{ display: 'flex', gap: 10, marginBottom: 16, flexWrap: 'wrap', alignItems: 'center' }}>
                <input type="text" placeholder="Suchen..." value={search} onChange={e => setSearch(e.target.value)}
                    style={{ flex: 1, minWidth: 180, padding: '8px 12px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: 13 }} />

                <select value={filterType} onChange={e => setFilterType(e.target.value)}
                    style={{ padding: '8px 12px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: 13 }}>
                    <option value="all">Alle Typen</option>
                    {Object.entries(TYPE_META).map(([k, v]) => <option key={k} value={k}>{v.icon} {v.label}</option>)}
                </select>

                <div style={{ display: 'flex', gap: 6 }}>
                    {[
                        { key: 'all', label: 'Alle' },
                        { key: 'up', label: '● Online', color: '#34d399' },
                        { key: 'down', label: '● Offline', color: '#ef4444' },
                    ].map(f => (
                        <button key={f.key} onClick={() => setFilterStatus(f.key)} style={{
                            padding: '7px 14px', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: 'pointer',
                            border: `1px solid ${filterStatus === f.key ? 'var(--accent)' : 'var(--border-color)'}`,
                            background: filterStatus === f.key ? 'var(--accent)' : 'var(--bg-secondary)',
                            color: filterStatus === f.key ? '#fff' : f.color || 'var(--text-primary)',
                        }}>{f.label}</button>
                    ))}
                </div>
            </div>

            <div style={{ color: 'var(--text-muted)', fontSize: 12, marginBottom: 12 }}>
                {filtered.length} von {devices.length} Geräten
            </div>

            {/* Empty State */}
            {devices.length === 0 && (
                <div className="card" style={{ padding: 60, textAlign: 'center', color: 'var(--text-muted)' }}>
                    <div style={{ fontSize: 48, marginBottom: 12 }}>📡</div>
                    <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 8 }}>Noch keine Geräte</div>
                    <div style={{ fontSize: 13, marginBottom: 20 }}>Füge Switches, Router, Server oder Services hinzu</div>
                    <button onClick={() => setShowForm(true)} style={{ padding: '9px 20px', borderRadius: 8, border: 'none', background: 'var(--accent)', color: '#fff', cursor: 'pointer', fontWeight: 600 }}>
                        + Erstes Gerät hinzufügen
                    </button>
                </div>
            )}

            {/* Device Grid */}
            {filtered.length > 0 && (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
                    {filtered.map(d => <DeviceCard key={d.id} device={d} onClick={() => setSelected(d)} />)}
                </div>
            )}

            {filtered.length === 0 && devices.length > 0 && (
                <div className="card" style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>
                    Keine Geräte gefunden
                </div>
            )}

            {/* Modals */}
            {selected && (
                <DetailModal
                    device={selected}
                    onClose={() => setSelected(null)}
                    onEdit={d => { setEditDevice(d); setShowForm(true); }}
                    onDelete={d => { handleDelete(d); setSelected(null); }}
                    onCheckNow={networkMonitorService.checkNow}
                />
            )}
            {showForm && (
                <DeviceFormModal
                    device={editDevice}
                    onSave={handleSave}
                    onClose={() => { setShowForm(false); setEditDevice(null); }}
                />
            )}
            {showDiscover && (
                <DiscoverModal
                    onClose={() => setShowDiscover(false)}
                    onAdd={handleSave}
                />
            )}
        </div>
    );
}
