import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext';
import riskService from '../services/riskService';
import { toast } from 'react-toastify';

const CATEGORIES = ['Identität & Zugriff', 'Geräte & Endpunkte', 'Incident / Bedrohung', 'IT-Sicherheit', 'Infrastruktur', 'Datenschutz', 'Sonstiges'];
const STATUSES   = ['offen', 'in_bearbeitung', 'akzeptiert', 'behoben'];
const STATUS_LABEL = { offen: 'Offen', in_bearbeitung: 'In Bearbeitung', akzeptiert: 'Akzeptiert', behoben: 'Behoben' };
const STATUS_COLOR = { offen: '#ef4444', in_bearbeitung: '#f59e0b', akzeptiert: '#6b7280', behoben: '#22c55e' };

const SOURCE_LABEL = {
    manual:           '✏️ Manuell',
    secure_score:     '🔒 Secure Score',
    risky_user:       '👤 Risky User',
    defender_alert:   '🛡️ Defender',
    noncompliant_device: '💻 Intune',
    no_mfa:           '🔑 MFA',
};

function riskColor(score) {
    if (score >= 20) return '#ef4444';
    if (score >= 12) return '#f97316';
    if (score >= 6)  return '#f59e0b';
    return '#22c55e';
}
function riskLabel(score) {
    if (score >= 20) return 'Kritisch';
    if (score >= 12) return 'Hoch';
    if (score >= 6)  return 'Mittel';
    return 'Niedrig';
}

const EMPTY_FORM = {
    title: '', description: '', category: 'Sonstiges',
    probability: 3, impact: 3, status: 'offen',
    responsible: '', mitigation: '', due_date: '',
};

export default function RiskPage() {
    const { isAdmin } = useAuth();
    const canEdit = isAdmin();

    const [risks, setRisks]       = useState([]);
    const [stats, setStats]       = useState(null);
    const [loading, setLoading]   = useState(true);
    const [syncing, setSyncing]   = useState(false);
    const [showModal, setShowModal] = useState(false);
    const [editing, setEditing]   = useState(null);
    const [form, setForm]         = useState(EMPTY_FORM);
    const [saving, setSaving]     = useState(false);
    const [expandedId, setExpandedId] = useState(null);
    const [filterStatus, setFilterStatus] = useState('');
    const [filterCat, setFilterCat]       = useState('');
    const [deleteConfirm, setDeleteConfirm] = useState(null);

    const load = useCallback(async () => {
        try {
            const params = {};
            if (filterStatus) params.status   = filterStatus;
            if (filterCat)    params.category = filterCat;
            const [data, s] = await Promise.all([riskService.getAll(params), riskService.getStats()]);
            setRisks(data);
            setStats(s);
        } catch { toast.error('Fehler beim Laden'); }
        finally { setLoading(false); }
    }, [filterStatus, filterCat]);

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

    const doSync = async () => {
        setSyncing(true);
        try {
            const result = await riskService.sync();
            toast.success(`Sync abgeschlossen: ${result.created} erfasst, ${result.errors.length} Fehler`);
            if (result.errors.length) result.errors.forEach(e => toast.warn(e, { autoClose: 8000 }));
            load();
        } catch (e) { toast.error(`Sync fehlgeschlagen: ${e.response?.data?.message || e.message}`); }
        finally { setSyncing(false); }
    };

    const openNew  = () => { setEditing(null); setForm(EMPTY_FORM); setShowModal(true); };
    const openEdit = (r) => {
        setEditing(r);
        setForm({
            title: r.title, description: r.description || '', category: r.category,
            probability: r.probability, impact: r.impact, status: r.status,
            responsible: r.responsible || '', mitigation: r.mitigation || '',
            due_date: r.due_date || '',
        });
        setShowModal(true);
    };

    const save = async () => {
        if (!form.title.trim()) return;
        setSaving(true);
        try {
            if (editing) { await riskService.update(editing.id, form); toast.success('Gespeichert'); }
            else         { await riskService.create(form);             toast.success('Risiko erstellt'); }
            setShowModal(false);
            load();
        } catch { toast.error('Fehler beim Speichern'); }
        finally { setSaving(false); }
    };

    const doDelete = async () => {
        try { await riskService.delete(deleteConfirm.id); toast.success('Gelöscht'); setDeleteConfirm(null); load(); }
        catch { toast.error('Fehler beim Löschen'); }
    };

    const ProbImpactBtn = ({ field, val }) => (
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[1,2,3,4,5].map(n => (
                <button key={n} onClick={() => setForm(f => ({ ...f, [field]: n }))} style={{
                    width: 34, height: 34, borderRadius: 8, border: '1px solid',
                    borderColor: form[field] === n ? riskColor(n * (field === 'probability' ? form.impact : form.probability)) : '#334155',
                    background: form[field] === n ? riskColor(n * (field === 'probability' ? form.impact : form.probability)) + '22' : 'transparent',
                    color: form[field] === n ? riskColor(n * (field === 'probability' ? form.impact : form.probability)) : '#64748b',
                    fontWeight: 700, cursor: 'pointer', fontSize: 13,
                }}>{n}</button>
            ))}
        </div>
    );

    if (loading) return <div style={{ display: 'flex', justifyContent: 'center', padding: '3rem' }}><div className="spinner" /></div>;

    return (
        <div style={{ maxWidth: 1400, margin: '0 auto' }}>
            {/* Header */}
            <div className="page-header" style={{ marginBottom: '1.5rem', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
                <div>
                    <h1 style={{ margin: 0, fontSize: '1.5rem', fontWeight: 700, color: '#f1f5f9' }}>⚠️ Risikoanalyse</h1>
                    <p style={{ margin: '4px 0 0', color: '#64748b', fontSize: 14 }}>Automatisch aus M365 + manuell erfasste Risiken</p>
                </div>
                {canEdit && (
                    <div style={{ display: 'flex', gap: 8 }}>
                        <button onClick={doSync} disabled={syncing} style={{
                            background: 'rgba(59,130,246,0.12)', border: '1px solid rgba(59,130,246,0.3)',
                            color: '#3b82f6', borderRadius: 8, padding: '8px 16px', cursor: 'pointer', fontWeight: 600, fontSize: 14,
                        }}>{syncing ? '⟳ Synchronisiere...' : '🔄 M365 Sync'}</button>
                        <button onClick={openNew} style={{
                            background: 'rgba(13,148,136,0.12)', border: '1px solid rgba(13,148,136,0.3)',
                            color: '#0d9488', borderRadius: 8, padding: '8px 16px', cursor: 'pointer', fontWeight: 600, fontSize: 14,
                        }}>+ Risiko erfassen</button>
                    </div>
                )}
            </div>

            {/* Stats */}
            {stats && (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 24 }}>
                    {[
                        { label: 'Gesamt',    value: stats.total,    color: '#94a3b8' },
                        { label: 'Kritisch',  value: stats.kritisch, color: '#ef4444' },
                        { label: 'Hoch',      value: stats.hoch,     color: '#f97316' },
                        { label: 'Mittel',    value: stats.mittel,   color: '#f59e0b' },
                        { label: 'Behoben',   value: stats.behoben,  color: '#22c55e' },
                    ].map(s => (
                        <div key={s.label} className="card" style={{ padding: '1rem', textAlign: 'center' }}>
                            <div style={{ fontSize: '1.75rem', fontWeight: 700, color: s.color }}>{s.value}</div>
                            <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>{s.label}</div>
                        </div>
                    ))}
                </div>
            )}

            {/* Risikomatrix (3x3 visual) */}
            <div className="card" style={{ padding: '1.25rem', marginBottom: 24 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#94a3b8', marginBottom: 12 }}>Risikomatrix</div>
                <div style={{ display: 'grid', gridTemplateColumns: '24px repeat(5,1fr)', gap: 4, fontSize: 11 }}>
                    {[5,4,3,2,1].map(prob => (
                        <React.Fragment key={prob}>
                            <div style={{ color: '#475569', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600 }}>{prob}</div>
                            {[1,2,3,4,5].map(imp => {
                                const score = prob * imp;
                                const col = riskColor(score);
                                const count = risks.filter(r => r.probability === prob && r.impact === imp && r.status !== 'behoben').length;
                                return (
                                    <div key={imp} style={{
                                        background: col + '20', border: `1px solid ${col}30`,
                                        borderRadius: 6, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
                                        color: count > 0 ? col : '#334155', fontWeight: count > 0 ? 700 : 400, fontSize: 13,
                                    }}>{count > 0 ? count : ''}</div>
                                );
                            })}
                        </React.Fragment>
                    ))}
                    <div />
                    {[1,2,3,4,5].map(n => (
                        <div key={n} style={{ color: '#475569', textAlign: 'center', fontWeight: 600, paddingTop: 4 }}>{n}</div>
                    ))}
                </div>
                <div style={{ display: 'flex', gap: 16, marginTop: 8, fontSize: 11, color: '#64748b' }}>
                    <span>↑ Wahrscheinlichkeit</span><span>→ Auswirkung</span>
                </div>
            </div>

            {/* Filter */}
            <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
                {['', ...STATUSES].map(s => (
                    <button key={s} onClick={() => setFilterStatus(s)} style={{
                        padding: '5px 14px', borderRadius: 20, border: '1px solid',
                        borderColor: filterStatus === s ? '#0d9488' : '#334155',
                        background: filterStatus === s ? 'rgba(13,148,136,0.12)' : 'transparent',
                        color: filterStatus === s ? '#0d9488' : '#64748b',
                        cursor: 'pointer', fontSize: 13, fontWeight: 500,
                    }}>{s === '' ? 'Alle' : STATUS_LABEL[s]}</button>
                ))}
                <select value={filterCat} onChange={e => setFilterCat(e.target.value)} className="form-select" style={{ fontSize: 13, padding: '4px 10px', minWidth: 160 }}>
                    <option value="">Alle Kategorien</option>
                    {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                </select>
            </div>

            {/* Risk list */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {risks.length === 0 && (
                    <div className="card" style={{ padding: '2rem', textAlign: 'center', color: '#475569' }}>
                        Keine Risiken erfasst. Klicke auf "M365 Sync" um automatisch Risiken zu importieren.
                    </div>
                )}
                {risks.map(risk => {
                    const score = risk.probability * risk.impact;
                    const col = riskColor(score);
                    const isExpanded = expandedId === risk.id;
                    return (
                        <div key={risk.id} className="card" style={{
                            padding: 0, overflow: 'hidden', cursor: 'pointer',
                            borderLeft: `3px solid ${col}`,
                        }} onClick={() => setExpandedId(isExpanded ? null : risk.id)}>
                            <div style={{ padding: '0.875rem 1.125rem', display: 'flex', alignItems: 'center', gap: 12 }}>
                                {/* Score badge */}
                                <div style={{
                                    flexShrink: 0, width: 44, height: 44, borderRadius: 10,
                                    background: col + '18', border: `1px solid ${col}40`,
                                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                                    color: col, fontWeight: 700, fontSize: 16,
                                }}>
                                    {score}
                                    <span style={{ fontSize: 9, fontWeight: 600, marginTop: 1 }}>{riskLabel(score)}</span>
                                </div>

                                <div style={{ flex: 1, minWidth: 0 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                                        <span style={{ fontWeight: 600, color: '#e2e8f0', fontSize: 14 }}>{risk.title}</span>
                                        <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 20, background: STATUS_COLOR[risk.status] + '18', color: STATUS_COLOR[risk.status], border: `1px solid ${STATUS_COLOR[risk.status]}40`, whiteSpace: 'nowrap' }}>
                                            {STATUS_LABEL[risk.status]}
                                        </span>
                                        <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 20, background: 'rgba(255,255,255,0.06)', color: '#64748b', border: '1px solid rgba(255,255,255,0.08)', whiteSpace: 'nowrap' }}>
                                            {SOURCE_LABEL[risk.source_type] || risk.source_type}
                                        </span>
                                        <span style={{ fontSize: 11, color: '#475569' }}>{risk.category}</span>
                                    </div>
                                    {!isExpanded && risk.description && (
                                        <div style={{ fontSize: 12, color: '#64748b', marginTop: 3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                            {risk.description}
                                        </div>
                                    )}
                                </div>

                                <div style={{ flexShrink: 0, textAlign: 'right', fontSize: 11, color: '#475569' }}>
                                    <div>W:{risk.probability} × A:{risk.impact}</div>
                                    {risk.responsible && <div style={{ marginTop: 2 }}>👤 {risk.responsible}</div>}
                                </div>
                            </div>

                            {isExpanded && (
                                <div style={{ padding: '0 1.125rem 1rem', borderTop: '1px solid rgba(255,255,255,0.05)' }} onClick={e => e.stopPropagation()}>
                                    {risk.description && <p style={{ fontSize: 13, color: '#94a3b8', margin: '12px 0 8px' }}>{risk.description}</p>}

                                    {/* MFA: Benutzerliste */}
                                    {risk.source_type === 'no_mfa' && risk.metadata?.users?.length > 0 && (
                                        <div style={{ marginBottom: 12 }}>
                                            <div style={{ fontSize: 12, fontWeight: 600, color: '#64748b', marginBottom: 6 }}>
                                                Benutzer ohne MFA ({risk.metadata.users.length}):
                                            </div>
                                            <div style={{ maxHeight: 200, overflowY: 'auto', borderRadius: 8, border: '1px solid rgba(255,255,255,0.06)', background: 'rgba(0,0,0,0.15)' }}>
                                                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                                                    <thead>
                                                        <tr style={{ borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
                                                            <th style={{ padding: '6px 10px', textAlign: 'left', color: '#64748b', fontWeight: 600 }}>Name</th>
                                                            <th style={{ padding: '6px 10px', textAlign: 'left', color: '#64748b', fontWeight: 600 }}>E-Mail</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {risk.metadata.users.map((u, i) => (
                                                            <tr key={i} style={{ borderBottom: '1px solid rgba(255,255,255,0.03)' }}>
                                                                <td style={{ padding: '5px 10px', color: '#e2e8f0' }}>{u.name || '–'}</td>
                                                                <td style={{ padding: '5px 10px', color: '#94a3b8' }}>{u.email}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    )}

                                    {/* Intune: Gerätedetails */}
                                    {risk.source_type === 'noncompliant_device' && risk.metadata && (
                                        <div style={{ marginBottom: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 12 }}>
                                            {[
                                                ['Gerät',        risk.metadata.deviceName],
                                                ['Benutzer',     risk.metadata.user],
                                                ['Betriebssystem', risk.metadata.os],
                                                ['Seriennummer', risk.metadata.serialNumber],
                                                ['Letzter Sync', risk.metadata.lastSync ? new Date(risk.metadata.lastSync).toLocaleDateString('de-DE') : null],
                                            ].filter(([,v]) => v).map(([k,v]) => (
                                                <div key={k} style={{ padding: '6px 10px', borderRadius: 6, background: 'rgba(0,0,0,0.15)', border: '1px solid rgba(255,255,255,0.06)' }}>
                                                    <div style={{ color: '#475569', fontSize: 11 }}>{k}</div>
                                                    <div style={{ color: '#e2e8f0', marginTop: 2 }}>{v}</div>
                                                </div>
                                            ))}
                                        </div>
                                    )}

                                    {/* Defender: Alert-Details */}
                                    {risk.source_type === 'defender_alert' && risk.metadata && (
                                        <div style={{ marginBottom: 12 }}>
                                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, fontSize: 12, marginBottom: 8 }}>
                                                {[
                                                    ['Schweregrad', risk.metadata.severity],
                                                    ['Kategorie',  risk.metadata.category],
                                                    ['Erkannt',    risk.metadata.detected ? new Date(risk.metadata.detected).toLocaleDateString('de-DE') : null],
                                                ].filter(([,v]) => v).map(([k,v]) => (
                                                    <div key={k} style={{ padding: '6px 10px', borderRadius: 6, background: 'rgba(0,0,0,0.15)', border: '1px solid rgba(255,255,255,0.06)' }}>
                                                        <div style={{ color: '#475569', fontSize: 11 }}>{k}</div>
                                                        <div style={{ color: '#e2e8f0', marginTop: 2 }}>{v}</div>
                                                    </div>
                                                ))}
                                            </div>
                                            {risk.metadata.entities?.length > 0 && (
                                                <div style={{ fontSize: 12, color: '#64748b', marginBottom: 6 }}>
                                                    <strong style={{ color: '#94a3b8' }}>Betroffene Entitäten:</strong> {risk.metadata.entities.join(', ')}
                                                </div>
                                            )}
                                            {risk.metadata.recommendation && (
                                                <div style={{ fontSize: 12, color: '#64748b', marginBottom: 6 }}>
                                                    <strong style={{ color: '#94a3b8' }}>Empfehlung:</strong> {risk.metadata.recommendation}
                                                </div>
                                            )}
                                            {risk.metadata.alertWebUrl && (
                                                <a href={risk.metadata.alertWebUrl} target="_blank" rel="noreferrer" style={{ fontSize: 12, color: '#0d9488' }}>
                                                    → Im Defender Portal öffnen
                                                </a>
                                            )}
                                        </div>
                                    )}

                                    {risk.mitigation && (
                                        <div style={{ fontSize: 13, color: '#64748b', marginBottom: 6 }}>
                                            <strong style={{ color: '#94a3b8' }}>Maßnahme:</strong> {risk.mitigation}
                                        </div>
                                    )}
                                    <div style={{ display: 'flex', gap: 16, fontSize: 12, color: '#475569', marginBottom: 10 }}>
                                        {risk.due_date && <span>📅 Fällig: {new Date(risk.due_date).toLocaleDateString('de-DE')}</span>}
                                        {risk.last_synced && <span>🔄 Sync: {new Date(risk.last_synced).toLocaleDateString('de-DE')}</span>}
                                    </div>
                                    {canEdit && (
                                        <div style={{ display: 'flex', gap: 8 }}>
                                            <button onClick={() => openEdit(risk)} style={{
                                                background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
                                                color: '#94a3b8', borderRadius: 6, padding: '4px 12px', cursor: 'pointer', fontSize: 12,
                                            }}>✏️ Bearbeiten</button>
                                            <button onClick={() => setDeleteConfirm(risk)} style={{
                                                background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)',
                                                color: '#ef4444', borderRadius: 6, padding: '4px 12px', cursor: 'pointer', fontSize: 12,
                                            }}>🗑️ Löschen</button>
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>

            {/* Modal */}
            {showModal && (
                <div className="modal-overlay" onClick={() => setShowModal(false)}>
                    <div className="modal-content modal-large" onClick={e => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>{editing ? 'Risiko bearbeiten' : 'Neues Risiko'}</h3>
                            <button className="modal-close" onClick={() => setShowModal(false)}>×</button>
                        </div>
                        <div className="modal-body">
                            <div className="form-group">
                                <label className="form-label">Titel *</label>
                                <input className="form-input" value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} placeholder="Risikobeschreibung" />
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                                <div className="form-group">
                                    <label className="form-label">Kategorie</label>
                                    <select className="form-select" value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))}>
                                        {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                                    </select>
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Status</label>
                                    <select className="form-select" value={form.status} onChange={e => setForm(f => ({ ...f, status: e.target.value }))}>
                                        {STATUSES.map(s => <option key={s} value={s}>{STATUS_LABEL[s]}</option>)}
                                    </select>
                                </div>
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                                <div className="form-group">
                                    <label className="form-label">Wahrscheinlichkeit (1-5) — aktuell: <strong style={{ color: riskColor(form.probability * form.impact) }}>{form.probability}</strong></label>
                                    <ProbImpactBtn field="probability" val={form.probability} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Auswirkung (1-5) — aktuell: <strong style={{ color: riskColor(form.probability * form.impact) }}>{form.impact}</strong></label>
                                    <ProbImpactBtn field="impact" val={form.impact} />
                                </div>
                            </div>
                            <div style={{ marginBottom: 12, padding: '8px 14px', borderRadius: 8, background: riskColor(form.probability * form.impact) + '18', border: `1px solid ${riskColor(form.probability * form.impact)}30` }}>
                                <span style={{ color: riskColor(form.probability * form.impact), fontWeight: 700 }}>
                                    Risikoscore: {form.probability * form.impact} — {riskLabel(form.probability * form.impact)}
                                </span>
                            </div>
                            <div className="form-group">
                                <label className="form-label">Beschreibung</label>
                                <textarea className="form-input" rows={3} value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} placeholder="Details zum Risiko..." />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Maßnahme / Mitigation</label>
                                <textarea className="form-input" rows={2} value={form.mitigation} onChange={e => setForm(f => ({ ...f, mitigation: e.target.value }))} placeholder="Was wird dagegen unternommen?" />
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                                <div className="form-group">
                                    <label className="form-label">Verantwortlicher</label>
                                    <input className="form-input" value={form.responsible} onChange={e => setForm(f => ({ ...f, responsible: e.target.value }))} placeholder="Name" />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Fälligkeitsdatum</label>
                                    <input type="date" className="form-input" value={form.due_date} onChange={e => setForm(f => ({ ...f, due_date: e.target.value }))} />
                                </div>
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button className="btn btn-secondary" onClick={() => setShowModal(false)}>Abbrechen</button>
                            <button className="btn btn-primary" onClick={save} disabled={saving || !form.title.trim()}>
                                {saving ? 'Speichern...' : 'Speichern'}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Delete confirm */}
            {deleteConfirm && (
                <div className="modal-overlay" onClick={() => setDeleteConfirm(null)}>
                    <div className="modal-content" onClick={e => e.stopPropagation()} style={{ maxWidth: 400 }}>
                        <div className="modal-header">
                            <h3>Risiko löschen</h3>
                            <button className="modal-close" onClick={() => setDeleteConfirm(null)}>×</button>
                        </div>
                        <div className="modal-body">
                            <p style={{ color: '#94a3b8' }}>„<strong style={{ color: '#f1f5f9' }}>{deleteConfirm.title}</strong>" wirklich löschen?</p>
                        </div>
                        <div className="modal-footer">
                            <button className="btn btn-secondary" onClick={() => setDeleteConfirm(null)}>Abbrechen</button>
                            <button className="btn btn-danger" onClick={doDelete}>Löschen</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
