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

const CATEGORIES = ['Infrastruktur & Betrieb', 'Benutzer & Arbeitsplätze', 'Systeme', 'IT-Governance & Compliance', 'Archiv'];
const STATUSES   = ['Offen', 'In Planung', 'In Umsetzung', 'Abgeschlossen'];
const PRIORITIES = ['Niedrig', 'Normal', 'Hoch', 'Kritisch'];

const STATUS_COLORS = {
    'Offen':          { bg: 'rgba(107,114,128,0.12)', text: '#6b7280', border: '#6b7280' },
    'In Planung':     { bg: 'rgba(59,130,246,0.12)',  text: '#3b82f6', border: '#3b82f6' },
    'In Umsetzung':   { bg: 'rgba(245,158,11,0.12)',  text: '#f59e0b', border: '#f59e0b' },
    'Abgeschlossen':  { bg: 'rgba(34,197,94,0.12)',   text: '#22c55e', border: '#22c55e' },
};

const PRIORITY_COLORS = {
    'Niedrig':  { text: '#6b7280', icon: '↓' },
    'Normal':   { text: '#3b82f6', icon: '→' },
    'Hoch':     { text: '#f59e0b', icon: '↑' },
    'Kritisch': { text: '#ef4444', icon: '⚡' },
};

const CAT_ICONS = {
    'Infrastruktur & Betrieb':     '🖥️',
    'Benutzer & Arbeitsplätze':    '👥',
    'Systeme':                     '💾',
    'IT-Governance & Compliance':  '🛡️',
    'Archiv':                      '📦',
};

const EMPTY_FORM = {
    title: '', category: 'Infrastruktur & Betrieb', status: 'Offen',
    priority: 'Normal', responsible: '', target_date: '', description: '', notes: '',
};

export default function ItOverviewPage() {
    const { isSuperAdmin, isAdmin, user } = useAuth();
    const canEdit = isSuperAdmin() || isAdmin();

    const [topics, setTopics]         = useState([]);
    const [loading, setLoading]       = useState(true);
    const [filterStatus, setFilterStatus] = useState('');
    const [filterCat, setFilterCat]   = useState('');
    const [showModal, setShowModal]   = useState(false);
    const [editing, setEditing]       = useState(null); // null = new
    const [form, setForm]             = useState(EMPTY_FORM);
    const [saving, setSaving]         = useState(false);
    const [deleteConfirm, setDeleteConfirm] = useState(null);
    const [expandedCard, setExpandedCard]   = useState(null);
    const [syncing, setSyncing]       = useState(false);
    const [lastSynced, setLastSynced] = useState(null);
    const [syncPulse, setSyncPulse]   = useState(false);

    const load = useCallback(async (silent = false) => {
        try {
            const params = {};
            if (filterStatus) params.status   = filterStatus;
            if (filterCat)    params.category = filterCat;
            const data = await itTopicService.getAll(params);
            setTopics(data);
            setLastSynced(new Date());
            if (silent) {
                setSyncPulse(true);
                setTimeout(() => setSyncPulse(false), 1200);
            }
        } catch {
            if (!silent) toast.error('Fehler beim Laden der IT-Themen');
        } finally {
            setLoading(false);
        }
    }, [filterStatus, filterCat]);

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

    // Auto-refresh every 10 seconds to pick up backend Planner sync changes
    useEffect(() => {
        const interval = setInterval(() => load(true), 10000);
        return () => clearInterval(interval);
    }, [load]);

    const openNew = () => {
        setEditing(null);
        setForm(EMPTY_FORM);
        setShowModal(true);
    };

    const openEdit = (topic) => {
        setEditing(topic);
        setForm({
            title:        topic.title        || '',
            category:     topic.category     || 'Infrastruktur',
            status:       topic.status       || 'Offen',
            priority:     topic.priority     || 'Normal',
            responsible:  topic.responsible  || '',
            target_date:  topic.target_date  || '',
            description:  topic.description  || '',
            notes:        topic.notes        || '',
        });
        setShowModal(true);
    };

    const handleSave = async () => {
        if (!form.title.trim()) { toast.error('Titel ist erforderlich'); return; }
        setSaving(true);
        try {
            if (editing) {
                await itTopicService.update(editing.id, form);
                toast.success('Thema aktualisiert');
            } else {
                await itTopicService.create(form);
                toast.success('Thema erstellt');
            }
            setShowModal(false);
            load();
        } catch {
            toast.error('Fehler beim Speichern');
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id) => {
        try {
            await itTopicService.delete(id);
            toast.success('Thema gelöscht');
            setDeleteConfirm(null);
            load();
        } catch {
            toast.error('Fehler beim Löschen');
        }
    };

    const handleSyncToPlanner = async () => {
        setSyncing(true);
        try {
            const result = await itTopicService.syncToPlanner();
            const parts = [];
            if (result.imported > 0) parts.push(`${result.imported} aus Planner importiert`);
            if (result.pulled   > 0) parts.push(`${result.pulled} Status übernommen`);
            if (result.created  > 0) parts.push(`${result.created} neu erstellt`);
            if (result.updated  > 0) parts.push(`${result.updated} aktualisiert`);
            if (result.errors   > 0) parts.push(`${result.errors} Fehler`);
            toast.success(`Planner sync: ${parts.join(', ') || 'Alles aktuell'}`);
            load(true);
        } catch (err) {
            const msg = err?.response?.data?.message || 'Fehler beim Planner-Sync';
            toast.error(msg);
        } finally {
            setSyncing(false);
        }
    };

    const handleStatusQuick = async (topic, newStatus) => {
        try {
            await itTopicService.update(topic.id, { status: newStatus });
            load();
        } catch {
            toast.error('Fehler beim Aktualisieren');
        }
    };

    // Group by category for kanban view
    const grouped = CATEGORIES.reduce((acc, cat) => {
        acc[cat] = topics.filter(t => t.category === cat);
        return acc;
    }, {});

    const visibleCats = filterCat ? [filterCat] : CATEGORIES;

    const totalCount       = topics.length;
    const abgeschlossen    = topics.filter(t => t.status === 'Abgeschlossen').length;
    const inUmsetzung      = topics.filter(t => t.status === 'In Umsetzung').length;
    const kritisch         = topics.filter(t => t.priority === 'Kritisch').length;

    return (
        <div className="main-content">
            <div className="container" style={{ maxWidth: '1600px' }}>
                {/* Header */}
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '24px', gap: '16px', flexWrap: 'wrap' }}>
                    <div>
                        <h1 style={{ fontSize: '24px', fontWeight: 700, margin: 0, color: 'var(--text-primary)' }}>
                            🗂️ IT Übersicht
                        </h1>
                        <p style={{ color: 'var(--text-secondary)', fontSize: '14px', margin: '4px 0 0' }}>
                            Strategische IT-Themen für die monatliche JF IT
                        </p>
                        {/* Planner Sync Status */}
                        <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginTop: '6px' }}>
                            <span style={{
                                width: '8px', height: '8px', borderRadius: '50%',
                                backgroundColor: syncPulse ? '#22c55e' : '#6b7280',
                                display: 'inline-block',
                                transition: 'background-color 0.3s',
                                boxShadow: syncPulse ? '0 0 0 3px rgba(34,197,94,0.3)' : 'none',
                            }} />
                            <span style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>
                                Planner Auto-Sync aktiv
                                {lastSynced && (
                                    <> · Abruf: {lastSynced.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</>
                                )}
                            </span>
                        </div>
                    </div>
                    {canEdit && (
                        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                            <button
                                className="btn btn-secondary"
                                onClick={handleSyncToPlanner}
                                disabled={syncing}
                                title="IT-Themen mit Microsoft Planner synchronisieren"
                                style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
                            >
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <path d="M20 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2Z"/>
                                    <path d="M12 12h.01"/>
                                    <path d="M8 12h.01"/>
                                    <path d="M16 12h.01"/>
                                </svg>
                                {syncing ? 'Synchronisiere...' : 'Planner sync'}
                            </button>
                            <button className="btn btn-primary" onClick={openNew}>
                                + Neues Thema
                            </button>
                        </div>
                    )}
                </div>

                {/* Stats */}
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '12px', marginBottom: '24px' }}>
                    {[
                        { label: 'Gesamt',        value: totalCount,    color: '#6b7280', icon: '📋' },
                        { label: 'In Umsetzung',  value: inUmsetzung,   color: '#f59e0b', icon: '🔄' },
                        { label: 'Abgeschlossen', value: abgeschlossen, color: '#22c55e', icon: '✅' },
                        { label: 'Kritisch',      value: kritisch,      color: '#ef4444', icon: '⚡' },
                    ].map(s => (
                        <div key={s.label} style={{
                            background: 'var(--bg-card)',
                            border: '1px solid var(--border-color)',
                            borderRadius: '10px',
                            padding: '14px 16px',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '12px',
                        }}>
                            <span style={{ fontSize: '22px' }}>{s.icon}</span>
                            <div>
                                <div style={{ fontSize: '22px', fontWeight: 700, color: s.color, lineHeight: 1 }}>{s.value}</div>
                                <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '2px' }}>{s.label}</div>
                            </div>
                        </div>
                    ))}
                </div>

                {/* Filters */}
                <div style={{ display: 'flex', gap: '10px', marginBottom: '20px', flexWrap: 'wrap', alignItems: 'center' }}>
                    <select
                        value={filterCat}
                        onChange={e => setFilterCat(e.target.value)}
                        className="form-select"
                        style={{ width: 'auto', minWidth: '160px', fontSize: '13px' }}
                    >
                        <option value="">Alle Kategorien</option>
                        {CATEGORIES.map(c => <option key={c} value={c}>{CAT_ICONS[c]} {c}</option>)}
                    </select>
                    <select
                        value={filterStatus}
                        onChange={e => setFilterStatus(e.target.value)}
                        className="form-select"
                        style={{ width: 'auto', minWidth: '140px', fontSize: '13px' }}
                    >
                        <option value="">Alle Status</option>
                        {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                    {(filterCat || filterStatus) && (
                        <button
                            className="btn btn-secondary btn-small"
                            onClick={() => { setFilterCat(''); setFilterStatus(''); }}
                        >
                            Filter zurücksetzen
                        </button>
                    )}
                </div>

                {/* Kanban Board */}
                {loading ? (
                    <div style={{ textAlign: 'center', padding: '60px', color: 'var(--text-muted)' }}>Lade...</div>
                ) : (
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: `repeat(${visibleCats.length}, minmax(280px, 1fr))`,
                        gap: '16px',
                        overflowX: 'auto',
                        paddingBottom: '16px',
                    }}>
                        {visibleCats.map(cat => {
                            const catTopics = grouped[cat] || [];
                            const sc = STATUS_COLORS;
                            return (
                                <div key={cat} style={{
                                    background: 'var(--bg-secondary)',
                                    border: '1px solid var(--border-color)',
                                    borderRadius: '12px',
                                    overflow: 'hidden',
                                    display: 'flex',
                                    flexDirection: 'column',
                                    minWidth: '280px',
                                }}>
                                    {/* Column header */}
                                    <div style={{
                                        padding: '14px 16px',
                                        borderBottom: '1px solid var(--border-color)',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        background: 'var(--bg-card)',
                                    }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                            <span style={{ fontSize: '18px' }}>{CAT_ICONS[cat]}</span>
                                            <span style={{ fontWeight: 700, fontSize: '14px', color: 'var(--text-primary)' }}>{cat}</span>
                                        </div>
                                        <span style={{
                                            background: 'var(--bg-secondary)',
                                            border: '1px solid var(--border-color)',
                                            borderRadius: '20px',
                                            padding: '2px 8px',
                                            fontSize: '12px',
                                            fontWeight: 600,
                                            color: 'var(--text-secondary)',
                                        }}>{catTopics.length}</span>
                                    </div>

                                    {/* Cards */}
                                    <div style={{ flex: 1, padding: '10px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                        {catTopics.length === 0 && (
                                            <div style={{
                                                padding: '24px 12px',
                                                textAlign: 'center',
                                                color: 'var(--text-muted)',
                                                fontSize: '13px',
                                            }}>
                                                Keine Themen
                                            </div>
                                        )}
                                        {catTopics.map(topic => {
                                            const sc = STATUS_COLORS[topic.status] || STATUS_COLORS['Offen'];
                                            const pc = PRIORITY_COLORS[topic.priority] || PRIORITY_COLORS['Normal'];
                                            const isExpanded = expandedCard === topic.id;
                                            const isAbgeschlossen = topic.status === 'Abgeschlossen';
                                            return (
                                                <div
                                                    key={topic.id}
                                                    style={{
                                                        background: 'var(--bg-card)',
                                                        border: '1px solid var(--border-color)',
                                                        borderLeft: `3px solid ${sc.border}`,
                                                        borderRadius: '8px',
                                                        padding: '12px',
                                                        opacity: isAbgeschlossen ? 0.7 : 1,
                                                        transition: 'box-shadow 0.15s',
                                                    }}
                                                    onMouseEnter={e => e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)'}
                                                    onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}
                                                >
                                                    {/* Title row */}
                                                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px', marginBottom: '8px' }}>
                                                        <span style={{ fontSize: '13px', color: pc.text, flexShrink: 0, fontWeight: 700 }} title={`Priorität: ${topic.priority}`}>
                                                            {pc.icon}
                                                        </span>
                                                        <span
                                                            style={{
                                                                fontWeight: 600,
                                                                fontSize: '13px',
                                                                color: 'var(--text-primary)',
                                                                flex: 1,
                                                                cursor: 'pointer',
                                                                textDecoration: isAbgeschlossen ? 'line-through' : 'none',
                                                            }}
                                                            onClick={() => setExpandedCard(isExpanded ? null : topic.id)}
                                                        >
                                                            {topic.title}
                                                        </span>
                                                        {topic.planner_task_id && (
                                                            <span
                                                                title="In Microsoft Planner synchronisiert"
                                                                style={{ fontSize: '11px', color: '#0078d4', flexShrink: 0 }}
                                                            >
                                                                📋
                                                            </span>
                                                        )}
                                                    </div>

                                                    {/* Status badge */}
                                                    <div style={{ marginBottom: '8px' }}>
                                                        <span style={{
                                                            background: sc.bg,
                                                            color: sc.text,
                                                            border: `1px solid ${sc.border}`,
                                                            borderRadius: '20px',
                                                            padding: '2px 8px',
                                                            fontSize: '11px',
                                                            fontWeight: 600,
                                                        }}>
                                                            {topic.status}
                                                        </span>
                                                    </div>

                                                    {/* Meta */}
                                                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', fontSize: '12px', color: 'var(--text-muted)' }}>
                                                        {topic.responsible && (
                                                            <span>👤 {topic.responsible}</span>
                                                        )}
                                                        {topic.target_date && (
                                                            <span>📅 {new Date(topic.target_date).toLocaleDateString('de-DE')}</span>
                                                        )}
                                                    </div>

                                                    {/* Expanded content */}
                                                    {isExpanded && (
                                                        <div style={{ marginTop: '10px', paddingTop: '10px', borderTop: '1px solid var(--border-color)' }}>
                                                            {topic.description && (
                                                                <div style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '8px', whiteSpace: 'pre-wrap' }}>
                                                                    {topic.description}
                                                                </div>
                                                            )}
                                                            {topic.notes && (
                                                                <div style={{
                                                                    background: 'rgba(245,158,11,0.08)',
                                                                    border: '1px solid rgba(245,158,11,0.2)',
                                                                    borderRadius: '6px',
                                                                    padding: '8px',
                                                                    fontSize: '12px',
                                                                    color: 'var(--text-secondary)',
                                                                    marginBottom: '8px',
                                                                    whiteSpace: 'pre-wrap',
                                                                }}>
                                                                    📝 {topic.notes}
                                                                </div>
                                                            )}
                                                        </div>
                                                    )}

                                                    {/* Actions */}
                                                    <div style={{ display: 'flex', gap: '6px', marginTop: '10px', flexWrap: 'wrap' }}>
                                                        {/* Quick status next step */}
                                                        {canEdit && topic.status !== 'Abgeschlossen' && (
                                                            <button
                                                                title="Status vorwärts"
                                                                onClick={() => {
                                                                    const idx = STATUSES.indexOf(topic.status);
                                                                    if (idx < STATUSES.length - 1) handleStatusQuick(topic, STATUSES[idx + 1]);
                                                                }}
                                                                style={{
                                                                    background: 'none',
                                                                    border: '1px solid var(--border-color)',
                                                                    borderRadius: '6px',
                                                                    padding: '3px 8px',
                                                                    fontSize: '11px',
                                                                    cursor: 'pointer',
                                                                    color: 'var(--text-secondary)',
                                                                }}
                                                            >
                                                                ▶ {STATUSES[STATUSES.indexOf(topic.status) + 1]}
                                                            </button>
                                                        )}
                                                        {canEdit && (
                                                            <>
                                                                <button
                                                                    onClick={() => openEdit(topic)}
                                                                    style={{
                                                                        background: 'none',
                                                                        border: '1px solid var(--border-color)',
                                                                        borderRadius: '6px',
                                                                        padding: '3px 8px',
                                                                        fontSize: '11px',
                                                                        cursor: 'pointer',
                                                                        color: 'var(--cereda-primary)',
                                                                        marginLeft: 'auto',
                                                                    }}
                                                                >
                                                                    ✏️
                                                                </button>
                                                                <button
                                                                    onClick={() => setDeleteConfirm(topic)}
                                                                    style={{
                                                                        background: 'none',
                                                                        border: '1px solid var(--border-color)',
                                                                        borderRadius: '6px',
                                                                        padding: '3px 8px',
                                                                        fontSize: '11px',
                                                                        cursor: 'pointer',
                                                                        color: '#ef4444',
                                                                    }}
                                                                >
                                                                    🗑️
                                                                </button>
                                                            </>
                                                        )}
                                                    </div>
                                                </div>
                                            );
                                        })}

                                        {/* Add button inside column */}
                                        {canEdit && !filterCat && !filterStatus && (
                                            <button
                                                onClick={() => { setForm({ ...EMPTY_FORM, category: cat }); setEditing(null); setShowModal(true); }}
                                                style={{
                                                    background: 'none',
                                                    border: '1px dashed var(--border-color)',
                                                    borderRadius: '8px',
                                                    padding: '10px',
                                                    fontSize: '13px',
                                                    cursor: 'pointer',
                                                    color: 'var(--text-muted)',
                                                    width: '100%',
                                                    transition: 'all 0.15s',
                                                }}
                                                onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--cereda-primary)'; e.currentTarget.style.color = 'var(--cereda-primary)'; }}
                                                onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-color)'; e.currentTarget.style.color = 'var(--text-muted)'; }}
                                            >
                                                + Thema hinzufügen
                                            </button>
                                        )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </div>

            {/* Modal: Create / Edit */}
            {showModal && (
                <div
                    style={{
                        position: 'fixed', inset: 0,
                        background: 'rgba(0,0,0,0.6)',
                        backdropFilter: 'blur(4px)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        zIndex: 1000, padding: '20px',
                    }}
                    onClick={e => { if (e.target === e.currentTarget) setShowModal(false); }}
                >
                    <div style={{
                        background: 'var(--bg-card)',
                        border: '1px solid var(--border-color)',
                        borderRadius: '20px',
                        width: '100%',
                        maxWidth: '580px',
                        maxHeight: '92vh',
                        overflowY: 'auto',
                        boxShadow: '0 24px 64px rgba(0,0,0,0.35)',
                    }}>
                        {/* Modal Header */}
                        <div style={{
                            padding: '22px 28px 20px',
                            borderBottom: '1px solid var(--border-color)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            background: 'linear-gradient(135deg, rgba(var(--cereda-primary-rgb,59,130,246),0.08) 0%, transparent 100%)',
                            borderRadius: '20px 20px 0 0',
                        }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                <div style={{
                                    width: '40px', height: '40px',
                                    borderRadius: '10px',
                                    background: 'rgba(59,130,246,0.15)',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    fontSize: '20px',
                                }}>
                                    {editing ? '✏️' : '🆕'}
                                </div>
                                <div>
                                    <div style={{ fontWeight: 700, fontSize: '17px', color: 'var(--text-primary)' }}>
                                        {editing ? 'Thema bearbeiten' : 'Neues IT-Thema'}
                                    </div>
                                    <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: '1px' }}>
                                        {editing ? editing.category : 'Für die JF IT Übersicht'}
                                    </div>
                                </div>
                            </div>
                            <button
                                onClick={() => setShowModal(false)}
                                style={{
                                    background: 'var(--bg-secondary)',
                                    border: '1px solid var(--border-color)',
                                    borderRadius: '8px',
                                    width: '32px', height: '32px',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    fontSize: '16px', cursor: 'pointer',
                                    color: 'var(--text-muted)',
                                }}
                            >
                                ×
                            </button>
                        </div>

                        <div style={{ padding: '24px 28px' }}>
                            {/* Titel */}
                            <div style={{ marginBottom: '20px' }}>
                                <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                    Titel *
                                </label>
                                <input
                                    className="form-input"
                                    value={form.title}
                                    onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
                                    placeholder="z.B. Migration auf Windows 11"
                                    autoFocus
                                    style={{ fontSize: '15px', fontWeight: 500 }}
                                />
                            </div>

                            {/* Kategorie + Status */}
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
                                <div>
                                    <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                        Kategorie
                                    </label>
                                    <select className="form-select" value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))} style={{ cursor: 'pointer' }}>
                                        {CATEGORIES.map(c => <option key={c} value={c}>{CAT_ICONS[c]} {c}</option>)}
                                    </select>
                                </div>
                                <div>
                                    <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                        Status
                                    </label>
                                    {/* Status als Chip-Auswahl */}
                                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                                        {STATUSES.map(s => {
                                            const sc = STATUS_COLORS[s];
                                            const active = form.status === s;
                                            return (
                                                <button
                                                    key={s}
                                                    type="button"
                                                    onClick={() => setForm(f => ({ ...f, status: s }))}
                                                    style={{
                                                        padding: '4px 10px',
                                                        borderRadius: '20px',
                                                        fontSize: '12px',
                                                        fontWeight: 600,
                                                        cursor: 'pointer',
                                                        border: `1.5px solid ${active ? sc.border : 'var(--border-color)'}`,
                                                        background: active ? sc.bg : 'transparent',
                                                        color: active ? sc.text : 'var(--text-muted)',
                                                        transition: 'all 0.15s',
                                                    }}
                                                >
                                                    {s}
                                                </button>
                                            );
                                        })}
                                    </div>
                                </div>
                            </div>

                            {/* Priorität + Zieldatum */}
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
                                <div>
                                    <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                        Priorität
                                    </label>
                                    {/* Priorität als Chip-Auswahl */}
                                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                                        {PRIORITIES.map(p => {
                                            const pc = PRIORITY_COLORS[p];
                                            const active = form.priority === p;
                                            return (
                                                <button
                                                    key={p}
                                                    type="button"
                                                    onClick={() => setForm(f => ({ ...f, priority: p }))}
                                                    style={{
                                                        padding: '4px 10px',
                                                        borderRadius: '20px',
                                                        fontSize: '12px',
                                                        fontWeight: 600,
                                                        cursor: 'pointer',
                                                        border: `1.5px solid ${active ? pc.text : 'var(--border-color)'}`,
                                                        background: active ? `${pc.text}18` : 'transparent',
                                                        color: active ? pc.text : 'var(--text-muted)',
                                                        transition: 'all 0.15s',
                                                    }}
                                                >
                                                    {pc.icon} {p}
                                                </button>
                                            );
                                        })}
                                    </div>
                                </div>
                                <div>
                                    <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                        Zieldatum
                                    </label>
                                    <input
                                        className="form-input"
                                        type="date"
                                        value={form.target_date}
                                        onChange={e => setForm(f => ({ ...f, target_date: e.target.value }))}
                                    />
                                </div>
                            </div>

                            {/* Verantwortlich */}
                            <div style={{ marginBottom: '16px' }}>
                                <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                    Verantwortlich
                                </label>
                                <input
                                    className="form-input"
                                    value={form.responsible}
                                    onChange={e => setForm(f => ({ ...f, responsible: e.target.value }))}
                                    placeholder="Name oder Team"
                                />
                            </div>

                            {/* Trennlinie */}
                            <div style={{ borderTop: '1px solid var(--border-color)', margin: '20px 0' }} />

                            {/* Beschreibung */}
                            <div style={{ marginBottom: '16px' }}>
                                <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                    Beschreibung
                                </label>
                                <textarea
                                    className="form-textarea"
                                    value={form.description}
                                    onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
                                    rows={3}
                                    placeholder="Was ist zu tun? Kontext, Hintergrund..."
                                    style={{ resize: 'vertical' }}
                                />
                            </div>

                            {/* Notizen */}
                            <div style={{ marginBottom: '4px' }}>
                                <label style={{ display: 'block', fontSize: '12px', fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '6px' }}>
                                    Notizen / Stand
                                </label>
                                <textarea
                                    className="form-textarea"
                                    value={form.notes}
                                    onChange={e => setForm(f => ({ ...f, notes: e.target.value }))}
                                    rows={2}
                                    placeholder="Aktueller Stand, offene Punkte..."
                                    style={{ resize: 'vertical' }}
                                />
                            </div>
                        </div>

                        {/* Modal Footer */}
                        <div style={{
                            padding: '16px 28px',
                            borderTop: '1px solid var(--border-color)',
                            display: 'flex',
                            gap: '10px',
                            justifyContent: 'flex-end',
                            background: 'var(--bg-secondary)',
                            borderRadius: '0 0 20px 20px',
                        }}>
                            <button className="btn btn-secondary" onClick={() => setShowModal(false)} disabled={saving}>
                                Abbrechen
                            </button>
                            <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
                                {saving ? 'Speichern...' : (editing ? '✓ Speichern' : '+ Erstellen')}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Delete confirm */}
            {deleteConfirm && (
                <div style={{
                    position: 'fixed', inset: 0,
                    background: 'rgba(0,0,0,0.5)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    zIndex: 1001, padding: '20px',
                }}>
                    <div style={{
                        background: 'var(--bg-card)',
                        border: '1px solid var(--border-color)',
                        borderRadius: '12px',
                        padding: '24px',
                        maxWidth: '400px',
                        width: '100%',
                    }}>
                        <h3 style={{ margin: '0 0 12px', color: 'var(--text-primary)' }}>Thema löschen?</h3>
                        <p style={{ color: 'var(--text-secondary)', fontSize: '14px', margin: '0 0 20px' }}>
                            <strong>"{deleteConfirm.title}"</strong> wird dauerhaft gelöscht.
                        </p>
                        <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
                            <button className="btn btn-secondary" onClick={() => setDeleteConfirm(null)}>Abbrechen</button>
                            <button className="btn btn-danger" onClick={() => handleDelete(deleteConfirm.id)}>Löschen</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
