import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '../context/AuthContext';
import onboardingProcessService from '../services/onboardingProcessService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';

const TAG_OPTIONS = [
    { value: 'normal',    label: 'Standard',  color: '#64748b' },
    { value: 'important', label: 'Wichtig',   color: '#f59e0b' },
    { value: 'critical',  label: 'Kritisch',  color: '#ef4444' },
];

const APPLIES_OPTIONS = [
    { value: 'both',        label: 'Onboarding & Offboarding' },
    { value: 'onboarding',  label: 'Nur Onboarding' },
    { value: 'offboarding', label: 'Nur Offboarding' },
];

const TEAM_OPTIONS = [
    { value: 'it',          label: 'IT',          color: '#3b82f6', icon: '💻' },
    { value: 'hr',          label: 'HR / Personal', color: '#10b981', icon: '🧑‍💼' },
    { value: 'buchhaltung', label: 'Buchhaltung',  color: '#8b5cf6', icon: '💶' },
];

const ICON_SUGGESTIONS = ['🔧','🛠️','💼','📊','📦','💻','🏢','🏭','🎓','📞','📋','🏪','🚗','🔑'];

// Rolle → responsible_team Mapping
const ROLE_TO_TEAM = {
    hr_personal:  'hr',
    buchhaltung:  'buchhaltung',
    support:      'it',
    admin:        null, // alle
    super_admin:  null, // alle
};

const TagBadge = ({ tag }) => {
    const t = TAG_OPTIONS.find(o => o.value === tag) || TAG_OPTIONS[0];
    return (
        <span style={{
            display: 'inline-block', padding: '1px 7px', borderRadius: 4,
            fontSize: '0.7rem', fontWeight: 700,
            background: t.color + '22', color: t.color,
        }}>{t.label}</span>
    );
};

const TeamBadge = ({ team }) => {
    const t = TEAM_OPTIONS.find(o => o.value === team) || TEAM_OPTIONS[0];
    return (
        <span style={{
            display: 'inline-block', padding: '1px 7px', borderRadius: 4,
            fontSize: '0.7rem', fontWeight: 700,
            background: t.color + '22', color: t.color,
        }}>{t.icon} {t.label}</span>
    );
};

const AppliesBadge = ({ val }) => {
    const colors = { both: '#64748b', onboarding: '#10b981', offboarding: '#ef4444' };
    const labels = { both: 'Beides', onboarding: 'Onboarding', offboarding: 'Offboarding' };
    return (
        <span style={{
            display: 'inline-block', padding: '1px 7px', borderRadius: 4,
            fontSize: '0.7rem', fontWeight: 600,
            background: (colors[val] || '#64748b') + '20',
            color: colors[val] || '#64748b',
        }}>{labels[val] || val}</span>
    );
};

const ProcessManagementPage = ({ embedded = false }) => {
    const { user, isAdmin, isSuperAdmin } = useAuth();
    const canManageDepts = isAdmin() || isSuperAdmin();
    const userTeam = ROLE_TO_TEAM[user?.role_name] !== undefined ? ROLE_TO_TEAM[user?.role_name] : null;
    const isAdminUser = canManageDepts;

    const [loading, setLoading] = useState(true);
    const [departments, setDepartments] = useState([]);
    const [processes, setProcesses] = useState([]);
    const [selectedDeptId, setSelectedDeptId] = useState(null);
    const [filterApplies, setFilterApplies] = useState('all');
    const [filterTeam, setFilterTeam] = useState(userTeam || 'all');

    // Department form
    const [showDeptForm, setShowDeptForm] = useState(false);
    const [editingDept, setEditingDept] = useState(null);
    const [deptForm, setDeptForm] = useState({ name: '', icon: '🏢' });

    // Process form
    const [showProcForm, setShowProcForm] = useState(false);
    const [editingProc, setEditingProc] = useState(null);
    const [procForm, setProcForm] = useState({
        title: '', description: '', applies_to: 'both', tag: 'normal',
        department_id: '', responsible_team: userTeam || 'it',
    });

    // Copy / Paste (bulk)
    const [copiedProcs, setCopiedProcs] = useState(null); // { sourceDeptId, items: [] }

    const copyTeamProcs = (teamValue, teamLabel) => {
        const teamProcs = processes.filter(p => p.department_id === selectedDeptId && p.responsible_team === teamValue);
        if (teamProcs.length === 0) { toast.warn('Keine Prozesse zum Kopieren'); return; }
        setCopiedProcs({ sourceDeptId: selectedDeptId, sourceTeam: teamValue, sourceTeamLabel: teamLabel, items: teamProcs });
        toast.info(`📋 ${teamProcs.length} ${teamLabel}-Prozesse kopiert`);
    };

    const pasteAllProcs = async () => {
        if (!copiedProcs) return;
        const targetDept = departments.find(d => d.id === selectedDeptId);
        if (!window.confirm(`${copiedProcs.items.length} Prozesse in "${targetDept?.name}" einfügen?`)) return;
        try {
            for (const proc of copiedProcs.items) {
                await onboardingProcessService.createProcess({
                    title: proc.title,
                    description: proc.description || '',
                    applies_to: proc.applies_to,
                    tag: proc.tag,
                    department_id: selectedDeptId,
                    responsible_team: proc.responsible_team,
                });
            }
            toast.success(`✅ ${copiedProcs.items.length} Prozesse eingefügt`);
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler beim Einfügen');
        }
    };

    // Drag & drop
    const dragItem = useRef(null);
    const dragOverItem = useRef(null);

    useEffect(() => {
        loadAll();
    }, []); // eslint-disable-line react-hooks/exhaustive-deps

    const loadAll = async () => {
        try {
            const [depts, procs] = await Promise.all([
                onboardingProcessService.getDepartments(),
                onboardingProcessService.getProcesses(),
            ]);
            setDepartments(depts);
            setProcesses(procs);
            if (!selectedDeptId && depts.length > 0) {
                setSelectedDeptId(depts[0].id);
            }
        } catch {
            toast.error('Fehler beim Laden');
        } finally {
            setLoading(false);
        }
    };

    // ── Department handlers ──────────────────────────────────────────────────
    const openDeptCreate = () => {
        setEditingDept(null);
        setDeptForm({ name: '', icon: '🏢' });
        setShowDeptForm(true);
    };

    const openDeptEdit = (dept) => {
        setEditingDept(dept);
        setDeptForm({ name: dept.name, icon: dept.icon });
        setShowDeptForm(true);
    };

    const submitDept = async (e) => {
        e.preventDefault();
        try {
            if (editingDept) {
                await onboardingProcessService.updateDepartment(editingDept.id, deptForm);
                toast.success('Abteilung aktualisiert');
            } else {
                const newDept = await onboardingProcessService.createDepartment(deptForm);
                setSelectedDeptId(newDept.id);
                toast.success('Abteilung erstellt');
            }
            setShowDeptForm(false);
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler beim Speichern');
        }
    };

    const deleteDept = async (dept) => {
        const procs = processes.filter(p => p.department_id === dept.id);
        const msg = procs.length > 0
            ? `Abteilung "${dept.name}" mit ${procs.length} Prozessen wirklich löschen?`
            : `Abteilung "${dept.name}" wirklich löschen?`;
        if (!window.confirm(msg)) return;
        try {
            await onboardingProcessService.deleteDepartment(dept.id);
            toast.success('Abteilung gelöscht');
            if (selectedDeptId === dept.id) setSelectedDeptId(null);
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler beim Löschen');
        }
    };

    // ── Process handlers ─────────────────────────────────────────────────────
    const openProcCreate = () => {
        setEditingProc(null);
        setProcForm({
            title: '', description: '', applies_to: 'both', tag: 'normal',
            department_id: selectedDeptId || '',
            responsible_team: userTeam || 'it',
        });
        setShowProcForm(true);
    };

    const openProcEdit = (proc) => {
        setEditingProc(proc);
        setProcForm({
            title: proc.title,
            description: proc.description || '',
            applies_to: proc.applies_to,
            tag: proc.tag,
            department_id: proc.department_id,
            responsible_team: proc.responsible_team,
        });
        setShowProcForm(true);
    };

    const submitProc = async (e) => {
        e.preventDefault();
        try {
            if (editingProc) {
                await onboardingProcessService.updateProcess(editingProc.id, procForm);
                toast.success('Prozess aktualisiert');
            } else {
                await onboardingProcessService.createProcess(procForm);
                toast.success('Prozess erstellt');
            }
            setShowProcForm(false);
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler beim Speichern');
        }
    };

    const deleteProc = async (proc) => {
        if (!window.confirm(`Prozess "${proc.title}" wirklich löschen?`)) return;
        try {
            await onboardingProcessService.deleteProcess(proc.id);
            toast.success('Prozess gelöscht');
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler');
        }
    };

    const canEditProc = (proc) => {
        if (isAdminUser) return true;
        return proc.responsible_team === userTeam;
    };

    // ── Drag & drop ──────────────────────────────────────────────────────────
    const handleDragStart = (e, idx) => {
        dragItem.current = idx;
        e.dataTransfer.effectAllowed = 'move';
    };

    const handleDragEnter = (e, idx) => {
        dragOverItem.current = idx;
        e.preventDefault();
    };

    const handleDrop = async (e) => {
        e.preventDefault();
        if (dragItem.current === null || dragOverItem.current === null) return;
        if (dragItem.current === dragOverItem.current) return;

        const deptProcs = visibleProcesses.slice();
        const dragged = deptProcs.splice(dragItem.current, 1)[0];
        deptProcs.splice(dragOverItem.current, 0, dragged);
        dragItem.current = null;
        dragOverItem.current = null;

        const updatedProcs = processes.map(p => {
            const idx = deptProcs.findIndex(dp => dp.id === p.id);
            return idx >= 0 ? { ...p, sort_order: idx } : p;
        });
        setProcesses(updatedProcs);

        try {
            await onboardingProcessService.reorderProcesses(selectedDeptId, deptProcs.map(p => p.id));
        } catch {
            toast.error('Fehler beim Speichern der Reihenfolge');
            loadAll();
        }
    };

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

    const selectedDept = departments.find(d => d.id === selectedDeptId);
    const visibleProcesses = processes
        .filter(p => {
            if (p.department_id !== selectedDeptId) return false;
            // Nicht-Admins sehen nur ihr eigenes Team
            if (!isAdminUser && userTeam && p.responsible_team !== userTeam) return false;
            if (filterTeam !== 'all' && p.responsible_team !== filterTeam) return false;
            if (filterApplies === 'all') return true;
            return p.applies_to === filterApplies || p.applies_to === 'both';
        })
        .sort((a, b) => {
            // Erst nach Team gruppieren, dann sort_order
            const teamOrder = ['it', 'hr', 'buchhaltung'];
            const ta = teamOrder.indexOf(a.responsible_team);
            const tb = teamOrder.indexOf(b.responsible_team);
            if (ta !== tb) return ta - tb;
            return a.sort_order - b.sort_order || a.title.localeCompare(b.title);
        });

    // Prozesse nach Team gruppieren
    const processGroups = TEAM_OPTIONS
        .filter(t => !userTeam || t.value === userTeam || isAdminUser)
        .map(t => ({
            team: t,
            items: visibleProcesses.filter(p => p.responsible_team === t.value),
        }))
        .filter(g => g.items.length > 0 || (isAdminUser && filterTeam === 'all'));

    const content = (
        <>
                {/* Header – nur wenn nicht eingebettet */}
                {!embedded && (
                    <div style={{ marginBottom: 24 }}>
                        <h1 style={{ margin: 0, fontSize: '1.5rem', fontWeight: 700 }}>⚙️ Prozess-Verwaltung</h1>
                        <p style={{ margin: '4px 0 0', color: 'var(--text-muted)', fontSize: '0.875rem' }}>
                            Onboarding & Offboarding Checklisten konfigurieren
                        </p>
                    </div>
                )}

                <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: 20, alignItems: 'start' }}>
                    {/* ── Links: Firmenabteilungen ── */}
                    <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                            <span style={{ fontWeight: 700, fontSize: '0.78rem', textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-secondary)' }}>
                                Abteilungen
                            </span>
                            {canManageDepts && (
                                <button onClick={openDeptCreate} className="btn btn-primary btn-small">+ Neu</button>
                            )}
                        </div>

                        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                            {departments.length === 0 && (
                                <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem' }}>Keine Abteilungen vorhanden</p>
                            )}
                            {departments.map(dept => {
                                const procCount = processes.filter(p =>
                                    p.department_id === dept.id &&
                                    (!userTeam || isAdminUser || p.responsible_team === userTeam)
                                ).length;
                                const isSelected = dept.id === selectedDeptId;
                                return (
                                    <div
                                        key={dept.id}
                                        onClick={() => setSelectedDeptId(dept.id)}
                                        style={{
                                            display: 'flex', alignItems: 'center', gap: 8,
                                            padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                                            background: isSelected ? 'var(--cereda-primary)' : 'var(--bg-card)',
                                            color: isSelected ? '#fff' : 'var(--text-primary)',
                                            border: `1px solid ${isSelected ? 'var(--cereda-primary)' : 'var(--border-color)'}`,
                                            transition: 'all 0.15s',
                                        }}
                                    >
                                        <span style={{ fontSize: '1.1rem' }}>{dept.icon}</span>
                                        <span style={{ flex: 1, fontWeight: 600, fontSize: '0.88rem' }}>{dept.name}</span>
                                        <span style={{
                                            fontSize: '0.7rem', fontWeight: 700, padding: '1px 6px', borderRadius: 10,
                                            background: isSelected ? 'rgba(255,255,255,0.25)' : 'var(--bg-secondary)',
                                            color: isSelected ? '#fff' : 'var(--text-muted)',
                                        }}>{procCount}</span>
                                        {canManageDepts && (
                                            <div style={{ display: 'flex', gap: 2 }} onClick={e => e.stopPropagation()}>
                                                <button onClick={() => openDeptEdit(dept)} title="Bearbeiten"
                                                    style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '2px 3px', opacity: 0.7, color: isSelected ? '#fff' : 'var(--text-muted)', fontSize: '0.8rem' }}>✏️</button>
                                                <button onClick={() => deleteDept(dept)} title="Löschen"
                                                    style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '2px 3px', opacity: 0.7, color: isSelected ? '#fff' : '#ef4444', fontSize: '0.8rem' }}>🗑️</button>
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>

                    {/* ── Rechts: Prozesse ── */}
                    <div>
                        {!selectedDept ? (
                            <div className="card" style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-muted)' }}>
                                Abteilung auswählen
                            </div>
                        ) : (
                            <>
                                {/* Toolbar */}
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, flexWrap: 'wrap', gap: 8 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                        <span style={{ fontSize: '1.3rem' }}>{selectedDept.icon}</span>
                                        <h2 style={{ margin: 0, fontSize: '1.1rem', fontWeight: 700 }}>{selectedDept.name}</h2>
                                    </div>
                                    <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                                        <select className="form-select" style={{ padding: '5px 10px', fontSize: '0.82rem', width: 'auto' }}
                                            value={filterApplies} onChange={e => setFilterApplies(e.target.value)}>
                                            <option value="all">Alle Typen</option>
                                            <option value="onboarding">Onboarding</option>
                                            <option value="offboarding">Offboarding</option>
                                        </select>
                                        {isAdminUser && (
                                            <select className="form-select" style={{ padding: '5px 10px', fontSize: '0.82rem', width: 'auto' }}
                                                value={filterTeam} onChange={e => setFilterTeam(e.target.value)}>
                                                <option value="all">Alle Teams</option>
                                                {TEAM_OPTIONS.map(t => <option key={t.value} value={t.value}>{t.icon} {t.label}</option>)}
                                            </select>
                                        )}
                                        {copiedProcs && copiedProcs.sourceDeptId !== selectedDeptId && (
                                            <button onClick={pasteAllProcs} className="btn btn-secondary btn-small" title="Kopierte Prozesse einfügen">
                                                📋 {copiedProcs.items.length} {copiedProcs.sourceTeamLabel} einfügen
                                            </button>
                                        )}
                                        <button onClick={openProcCreate} className="btn btn-primary btn-small">+ Prozess hinzufügen</button>
                                    </div>
                                </div>

                                {/* Prozesse nach Team gruppiert */}
                                {visibleProcesses.length === 0 ? (
                                    <div className="card" style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-muted)' }}>
                                        Noch keine Prozesse. Klicke auf „+ Prozess hinzufügen".
                                    </div>
                                ) : (
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                                        {processGroups.map(({ team, items }) => items.length === 0 ? null : (
                                            <div key={team.value}>
                                                {/* Team-Header */}
                                                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, paddingBottom: 6, borderBottom: `2px solid ${team.color}33` }}>
                                                    <span>{team.icon}</span>
                                                    <span style={{ fontWeight: 700, fontSize: '0.88rem', color: team.color }}>{team.label}</span>
                                                    <span style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>{items.length} Aufgaben</span>
                                                    <button
                                                        onClick={() => copyTeamProcs(team.value, team.label)}
                                                        className="btn btn-secondary btn-small"
                                                        title={`${team.label}-Prozesse kopieren`}
                                                        style={{
                                                            marginLeft: 'auto', fontSize: '0.72rem', padding: '2px 8px',
                                                            background: copiedProcs?.sourceDeptId === selectedDeptId && copiedProcs?.sourceTeam === team.value ? team.color + '22' : undefined,
                                                            color: copiedProcs?.sourceDeptId === selectedDeptId && copiedProcs?.sourceTeam === team.value ? team.color : undefined,
                                                        }}>
                                                        📋 Kopieren
                                                    </button>
                                                </div>

                                                {/* Prozessliste */}
                                                <div
                                                    style={{ display: 'flex', flexDirection: 'column', gap: 5 }}
                                                    onDragOver={e => e.preventDefault()}
                                                    onDrop={handleDrop}
                                                >
                                                    {items.map((proc, idx) => (
                                                        <div
                                                            key={proc.id}
                                                            draggable={canEditProc(proc)}
                                                            onDragStart={e => handleDragStart(e, idx)}
                                                            onDragEnter={e => handleDragEnter(e, idx)}
                                                            style={{
                                                                display: 'flex', alignItems: 'flex-start', gap: 10,
                                                                padding: '10px 12px', borderRadius: 8,
                                                                background: 'var(--bg-card)',
                                                                border: '1px solid var(--border-color)',
                                                                cursor: canEditProc(proc) ? 'grab' : 'default',
                                                                borderLeft: `3px solid ${team.color}`,
                                                            }}
                                                        >
                                                            {canEditProc(proc) && (
                                                                <span style={{ color: 'var(--text-muted)', fontSize: '0.9rem', lineHeight: '1.5', userSelect: 'none', flexShrink: 0 }}>⋮⋮</span>
                                                            )}
                                                            <div style={{ flex: 1, minWidth: 0 }}>
                                                                <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 2 }}>
                                                                    <span style={{ fontWeight: 600, fontSize: '0.88rem' }}>{proc.title}</span>
                                                                    <TagBadge tag={proc.tag} />
                                                                    <AppliesBadge val={proc.applies_to} />
                                                                </div>
                                                                {proc.description && (
                                                                    <p style={{ margin: 0, fontSize: '0.78rem', color: 'var(--text-muted)', lineHeight: 1.4 }}>
                                                                        {proc.description}
                                                                    </p>
                                                                )}
                                                            </div>
                                                            {canEditProc(proc) && (
                                                                <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                                                                    <button onClick={() => openProcEdit(proc)} className="btn btn-secondary btn-small" title="Bearbeiten">✏️</button>
                                                                    <button onClick={() => deleteProc(proc)} className="btn btn-danger btn-small" title="Löschen">🗑️</button>
                                                                </div>
                                                            )}
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                </div>

            {/* ── Department Modal ── */}
            {showDeptForm && (
                <div className="modal-overlay" onClick={() => setShowDeptForm(false)}>
                    <div className="modal-content" style={{ maxWidth: 440 }} onClick={e => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2 className="modal-title">{editingDept ? 'Abteilung bearbeiten' : 'Neue Abteilung'}</h2>
                            <button className="modal-close" onClick={() => setShowDeptForm(false)}>×</button>
                        </div>
                        <form onSubmit={submitDept} style={{ padding: '0 24px 24px' }}>
                            <div className="form-group">
                                <label className="form-label">Name *</label>
                                <input className="form-input" type="text" placeholder="z.B. Wartung, Vertrieb AD"
                                    value={deptForm.name}
                                    onChange={e => setDeptForm({ ...deptForm, name: e.target.value })}
                                    required />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Icon</label>
                                <input className="form-input" type="text"
                                    value={deptForm.icon}
                                    onChange={e => setDeptForm({ ...deptForm, icon: e.target.value })}
                                    style={{ fontSize: '1.3rem', width: 60 }} />
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                                    {ICON_SUGGESTIONS.map(ic => (
                                        <button key={ic} type="button"
                                            onClick={() => setDeptForm({ ...deptForm, icon: ic })}
                                            style={{
                                                fontSize: '1.2rem', padding: '4px 8px', borderRadius: 6, cursor: 'pointer',
                                                border: `2px solid ${deptForm.icon === ic ? 'var(--cereda-primary)' : 'var(--border-color)'}`,
                                                background: deptForm.icon === ic ? 'var(--cereda-primary)10' : 'var(--bg-secondary)',
                                            }}>{ic}</button>
                                    ))}
                                </div>
                            </div>
                            <div className="card-footer" style={{ padding: 0 }}>
                                <button type="button" onClick={() => setShowDeptForm(false)} className="btn btn-secondary">Abbrechen</button>
                                <button type="submit" className="btn btn-primary">Speichern</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* ── Process Modal ── */}
            {showProcForm && (
                <div className="modal-overlay" onClick={() => setShowProcForm(false)}>
                    <div className="modal-content" style={{ maxWidth: 540 }} onClick={e => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2 className="modal-title">{editingProc ? 'Prozess bearbeiten' : 'Neuer Prozess'}</h2>
                            <button className="modal-close" onClick={() => setShowProcForm(false)}>×</button>
                        </div>
                        <form onSubmit={submitProc} style={{ padding: '0 24px 24px' }}>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                                <div className="form-group">
                                    <label className="form-label">Abteilung *</label>
                                    <select className="form-select"
                                        value={procForm.department_id}
                                        onChange={e => setProcForm({ ...procForm, department_id: Number(e.target.value) })}
                                        required>
                                        <option value="">— Bitte wählen —</option>
                                        {departments.map(d => (
                                            <option key={d.id} value={d.id}>{d.icon} {d.name}</option>
                                        ))}
                                    </select>
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Zuständig *</label>
                                    {isAdminUser ? (
                                        <select className="form-select"
                                            value={procForm.responsible_team}
                                            onChange={e => setProcForm({ ...procForm, responsible_team: e.target.value })}>
                                            {TEAM_OPTIONS.map(t => <option key={t.value} value={t.value}>{t.icon} {t.label}</option>)}
                                        </select>
                                    ) : (
                                        <input className="form-input" readOnly
                                            value={TEAM_OPTIONS.find(t => t.value === userTeam)?.label || userTeam} />
                                    )}
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="form-label">Titel *</label>
                                <input className="form-input" type="text" placeholder="z.B. AD-Account erstellen"
                                    value={procForm.title}
                                    onChange={e => setProcForm({ ...procForm, title: e.target.value })}
                                    required />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Beschreibung</label>
                                <textarea className="form-textarea" rows={3} placeholder="Optionale Details / Hinweise..."
                                    value={procForm.description}
                                    onChange={e => setProcForm({ ...procForm, description: e.target.value })} />
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                                <div className="form-group">
                                    <label className="form-label">Gilt für</label>
                                    <select className="form-select" value={procForm.applies_to}
                                        onChange={e => setProcForm({ ...procForm, applies_to: e.target.value })}>
                                        {APPLIES_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                                    </select>
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Priorität</label>
                                    <select className="form-select" value={procForm.tag}
                                        onChange={e => setProcForm({ ...procForm, tag: e.target.value })}>
                                        {TAG_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                                    </select>
                                </div>
                            </div>
                            <div className="card-footer" style={{ padding: 0 }}>
                                <button type="button" onClick={() => setShowProcForm(false)} className="btn btn-secondary">Abbrechen</button>
                                <button type="submit" className="btn btn-primary">Speichern</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </>
    );

    if (embedded) return content;
    return (
        <div className="main-content">
            <div className="container">{content}</div>
        </div>
    );
};

export default ProcessManagementPage;
