import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import ticketService from '../services/ticketService';
import fidoKeyService from '../services/fidoKeyService';
import aiService from '../services/aiService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';
import { marked } from 'marked';

marked.use({ breaks: true, gfm: true });
const renderMd = (text) => {
    try {
        const html = marked.parse(String(text || ''), { async: false });
        return { __html: typeof html === 'string' ? html : String(html) };
    } catch {
        return { __html: String(text || '').replace(/\n/g, '<br>') };
    }
};

/* ── Helpers ────────────────────────────────────────────────────── */

/* ── Klick-Assistent Themen ─────────────────────────────────────── */
const WIZARD_TOPICS = [
    {
        key: 'passwort', icon: '🔑', label: 'Passwort / Zugang',
        sub: 'Passwort vergessen, Konto gesperrt, kein Zugriff',
        category: 'Software', priority: 'hoch',
        titleTemplate: 'Passwort zurücksetzen',
        questions: [
            { id: 'konto',  label: 'Betroffenes Konto / System', placeholder: 'z.B. Windows, Outlook, VPN, SharePoint…', type: 'text',     required: true  },
            { id: 'fehler', label: 'Fehlermeldung (falls vorhanden)',  placeholder: 'z.B. „Benutzername oder Kennwort ist falsch"', type: 'text', required: false },
        ],
    },
    {
        key: 'email', icon: '📧', label: 'E-Mail / Outlook',
        sub: 'E-Mail geht nicht, Outlook abgestürzt, Postfach voll',
        category: 'Software', priority: 'mittel',
        titleTemplate: 'E-Mail / Outlook – Problem',
        questions: [
            { id: 'problem', label: 'Folgendes Problem tritt auf',        placeholder: 'z.B. Outlook startet nicht, E-Mails werden nicht gesendet…', type: 'textarea', required: true  },
            { id: 'seit',    label: 'Seit wann?',                         placeholder: 'z.B. heute Morgen, seit gestern Nachmittag…',                  type: 'text',     required: false },
            { id: 'fehler',  label: 'Fehlermeldung',                      placeholder: 'Fehlermeldung falls vorhanden…',                               type: 'text',     required: false },
        ],
    },
    {
        key: 'vpn', icon: '🌐', label: 'VPN / Fernzugriff',
        sub: 'VPN verbindet nicht, Homeoffice-Zugriff gestört',
        category: 'Software', priority: 'mittel',
        titleTemplate: 'VPN verbindet nicht',
        questions: [
            { id: 'bs',      label: 'Betriebssystem',  placeholder: 'Windows 10 / 11, macOS…',                           type: 'text',     required: false },
            { id: 'problem', label: 'Was passiert?',   placeholder: 'z.B. Verbindung bricht ab, Fehlermeldung erscheint…', type: 'textarea', required: true  },
            { id: 'fehler',  label: 'Fehlermeldung',   placeholder: 'Fehlermeldung falls vorhanden…',                    type: 'text',     required: false },
        ],
    },
    {
        key: 'drucker', icon: '🖨️', label: 'Drucker',
        sub: 'Druckt nicht, Papierstau, nicht gefunden',
        category: 'Hardware', priority: 'mittel',
        titleTemplate: 'Drucker funktioniert nicht',
        questions: [
            { id: 'modell',   label: 'Drucker-Modell',        placeholder: 'z.B. HP LaserJet Pro, Brother HL…',          type: 'text',     required: false },
            { id: 'standort', label: 'Standort des Druckers', placeholder: 'z.B. Büro 2. OG, Besprechungsraum…',         type: 'text',     required: false },
            { id: 'problem',  label: 'Was ist das Problem?',  placeholder: 'z.B. druckt nicht, Papierstau, nicht erkannt…', type: 'textarea', required: true  },
            { id: 'fehler',   label: 'Fehlermeldung',         placeholder: 'Fehlermeldung am Drucker oder PC…',          type: 'text',     required: false },
        ],
    },
    {
        key: 'pc', icon: '💻', label: 'PC / Laptop',
        sub: 'Startet nicht, langsam, Absturz, Bluescreen',
        category: 'Hardware', priority: 'mittel',
        titleTemplate: 'PC / Laptop – Problem',
        questions: [
            { id: 'geraet',  label: 'Gerät (Name oder Modell)', placeholder: 'z.B. Dell XPS 15, Lenovo ThinkPad…',        type: 'text',     required: false },
            { id: 'problem', label: 'Was ist das Problem?',     placeholder: 'z.B. startet nicht, Bluescreen, sehr langsam…', type: 'textarea', required: true  },
            { id: 'seit',    label: 'Seit wann?',               placeholder: 'z.B. nach letztem Update, heute Morgen…',   type: 'text',     required: false },
            { id: 'fehler',  label: 'Fehlermeldung',            placeholder: 'Fehlermeldung falls vorhanden…',            type: 'text',     required: false },
        ],
    },
    {
        key: 'software', icon: '⚙️', label: 'Software',
        sub: 'Installation, Update, Programm startet nicht',
        category: 'Software', priority: 'mittel',
        titleTemplate: 'Software – Problem',
        questions: [
            { id: 'programm', label: 'Programm / Software',                               placeholder: 'z.B. Adobe Acrobat, Microsoft Teams…',             type: 'text',     required: true  },
            { id: 'problem',  label: 'Was soll gemacht werden / was ist das Problem?',    placeholder: 'z.B. installieren, startet nicht, Fehler beim Öffnen…', type: 'textarea', required: true  },
            { id: 'fehler',   label: 'Fehlermeldung',                                     placeholder: 'Fehlermeldung falls vorhanden…',                    type: 'text',     required: false },
        ],
    },
    {
        key: 'selectline', icon: '📊', label: 'SelectLine',
        sub: 'Fehler, Absturz, Frage zu Funktionen',
        category: 'SelectLine', priority: 'hoch',
        titleTemplate: 'SelectLine – Problem',
        questions: [
            { id: 'modul',        label: 'Modul / Bereich',               placeholder: 'z.B. Auftragsbearbeitung, Lager, Fibu…',              type: 'text',     required: false },
            { id: 'problem',      label: 'Was ist das Problem?',          placeholder: 'z.B. Fehler beim Buchen, Absturz, Funktion fehlt…',   type: 'textarea', required: true  },
            { id: 'fehler',       label: 'Fehlermeldung',                 placeholder: 'Fehlermeldung falls vorhanden…',                     type: 'text',     required: false },
            { id: 'wiederholbar', label: 'Ist das Problem wiederholbar?', placeholder: 'Ja / Nein / Manchmal',                               type: 'text',     required: false },
        ],
    },
    {
        key: 'sonstiges', icon: '💬', label: 'Sonstiges',
        sub: 'Anderes IT-Problem beschreiben',
        category: 'Allgemein', priority: 'mittel',
        titleTemplate: '',
        questions: [
            { id: 'problem', label: 'Beschreibe dein Problem', placeholder: 'Was ist passiert? Was brauchst du?',    type: 'textarea', required: true  },
            { id: 'seit',    label: 'Seit wann?',              placeholder: 'z.B. heute, seit letzter Woche…',       type: 'text',     required: false },
        ],
    },
];

const buildDescription = (topic, answers) =>
    topic.questions
        .map(q => `${q.label}:\n${answers[q.id]?.trim() || '–'}`)
        .join('\n\n');

const detectOS = () => {
    const ua = navigator.userAgent;
    if (/Windows NT 1[01]/.test(ua)) return 'Windows 11/10';
    if (/Windows/.test(ua))  return 'Windows';
    if (/Mac OS X/.test(ua)) return 'macOS';
    if (/Android/.test(ua))  return 'Android';
    if (/iPhone|iPad/.test(ua)) return 'iOS';
    if (/Linux/.test(ua))    return 'Linux';
    return '';
};

const STATUS_CONFIG = {
    offen:                  { label: 'Offen',                  css: 'status-pending'     },
    in_bearbeitung:         { label: 'In Bearbeitung',         css: 'status-in_progress' },
    warten_auf_mitarbeiter: { label: 'Warten auf Mitarbeiter', css: 'status-completed'   },
    warten_auf_support:     { label: 'Warten auf Support',     css: 'status-warning'     },
    geschlossen:            { label: 'Geschlossen',            css: 'status-inaktiv'     },
};

const PRIORITY_CONFIG = {
    niedrig: { label: 'Niedrig', color: 'var(--success)'  },
    mittel:  { label: 'Mittel',  color: 'var(--info)'     },
    hoch:    { label: 'Hoch',    color: 'var(--warning)'  },
    kritisch:{ label: 'Kritisch',color: 'var(--danger)'   },
};

const ASSET_TYPE_ICONS = {
    Laptop: '💻', Desktop: '🖥️', Monitor: '🖥️', Drucker: '🖨️',
    Smartphone: '📱', Tablet: '📱', Server: '🖧', Sonstiges: '📦',
};

const FIDO_STATUS = {
    aktiv:   { label: 'Aktiv',   css: 'status-completed' },
    inaktiv: { label: 'Inaktiv', css: 'status-inaktiv'   },
    verloren:{ label: 'Verloren',css: 'status-pending'   },
};

const toUTC = (d) => d ? new Date(typeof d === 'string' && !d.endsWith('Z') && !d.includes('+') ? d.replace(' ', 'T') + 'Z' : d) : null;

const formatDate = (d) => {
    if (!d) return '–';
    const date = toUTC(d);
    const now  = new Date();
    const diff = Math.floor((now - date) / 1000);
    if (diff < 60)     return 'gerade eben';
    if (diff < 3600)   return `vor ${Math.floor(diff / 60)} Min`;
    if (diff < 86400)  return `vor ${Math.floor(diff / 3600)} Std`;
    if (diff < 604800) return `vor ${Math.floor(diff / 86400)} Tagen`;
    return date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });
};

/* ── Ticket Card ────────────────────────────────────────────────── */
const TicketCard = ({ ticket, onClick }) => {
    const prioColor  = PRIORITY_CONFIG[ticket.priority]?.color || 'var(--text-muted)';
    const statusConf = STATUS_CONFIG[ticket.status] || {};

    return (
        <div onClick={onClick} style={{
            background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
            borderRadius: '10px', overflow: 'hidden', cursor: 'pointer',
            transition: 'box-shadow 0.18s, border-color 0.18s, transform 0.15s',
        }}
            onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.15)'; e.currentTarget.style.borderColor = 'var(--cereda-primary)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
            onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = 'var(--border-color)'; e.currentTarget.style.transform = 'translateY(0)'; }}
        >
            <div style={{ height: '3px', background: prioColor }} />
            <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ fontFamily: 'monospace', fontSize: '0.725rem', fontWeight: 700, color: 'var(--cereda-primary)' }}>
                        {ticket.ticket_number}
                    </span>
                    <span className={`status-badge ${statusConf.css}`} style={{ fontSize: '0.65rem' }}>
                        {statusConf.label}
                    </span>
                </div>
                <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text-primary)', lineHeight: 1.35 }}>
                    {ticket.title}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ fontSize: '0.725rem', color: 'var(--text-muted)' }}>{formatDate(ticket.created_at)}</span>
                    <span style={{ fontSize: '0.725rem', color: prioColor, fontWeight: 600 }}>
                        {PRIORITY_CONFIG[ticket.priority]?.label}
                    </span>
                </div>
            </div>
        </div>
    );
};

/* ══════════════════════════════════════════════════════════════════
   UserPortalPage
══════════════════════════════════════════════════════════════════ */
const UserPortalPage = () => {
    const navigate  = useNavigate();
    const { user }  = useAuth();

    const [loading,      setLoading]      = useState(true);
    const [tickets,      setTickets]      = useState([]);
    const [assets,       setAssets]       = useState([]);
    const [fidoKeys,     setFidoKeys]     = useState([]);
    const [showModal,       setShowModal]       = useState(false);
    const [wizardStep,      setWizardStep]      = useState(0); // 0 = Thema wählen, 1 = Fragen, 2 = Defekt (direkt)
    const [selectedTopic,   setSelectedTopic]   = useState(null);
    const [questionAnswers, setQuestionAnswers] = useState({});
    const [formAssets,      setFormAssets]      = useState([]);
    const [formLoading,     setFormLoading]     = useState(false);
    const [categories,      setCategories]      = useState([]);
    const [activeTab,    setActiveTab]    = useState('anfragen'); // 'anfragen' | 'geraete' | 'fido' | 'ki' | 'einstellungen'
    const [ticketFilter, setTicketFilter] = useState('aktiv');   // 'aktiv' | 'alle'

    // Einstellungen
    const [emailNotif,     setEmailNotif]     = useState(user?.email_notifications !== 0);
    const [savingNotif,    setSavingNotif]    = useState(false);

    const STAFF_ROLES = ['super_admin', 'admin', 'support', 'bearbeiter'];
    const isStaff = STAFF_ROLES.includes(user?.role_name);
    const [staffNotif, setStaffNotif] = useState({
        notif_ticket_created:  user?.notif_ticket_created  ?? false,
        notif_ticket_assigned: user?.notif_ticket_assigned ?? true,
        notif_new_comment:     user?.notif_new_comment     ?? true,
        notif_weekly_report:   user?.notif_weekly_report   ?? true,
    });
    const [savingStaffNotif, setSavingStaffNotif] = useState(false);

    // KI-Chat State
    const KI_WELCOME = { role: 'assistant', content: 'Hallo! Ich bin dein persönlicher IT-Assistent. Beschreibe mir dein Problem – ich helfe dir Schritt für Schritt weiter.\n\nWenn ich dir nicht weiterhelfen kann, kannst du jederzeit ein Support-Ticket erstellen.' };
    const [kiMessages,  setKiMessages]  = useState([KI_WELCOME]);
    const [kiInput,     setKiInput]     = useState('');
    const [kiLoading,   setKiLoading]   = useState(false);
    const kiBottomRef = useRef(null);
    const kiInputRef  = useRef(null);

    const [formData, setFormData] = useState({
        title: '', description: '', category: 'Allgemein', priority: 'mittel', asset_id: '',
    });

    useEffect(() => {
        loadAll();
        api.get('/settings/categories').then(r => setCategories(r.data)).catch(() => {});
    }, []); // eslint-disable-line react-hooks/exhaustive-deps

    const loadAll = async () => {
        try {
            const [ticketData, assetData, fidoData] = await Promise.all([
                ticketService.getAll().catch(() => []),
                api.get('/assets/mine').then(r => r.data.data).catch(() => []),
                fidoKeyService.getAll().then(keys =>
                    keys.filter(k => k.assigned_to_user_id === user?.id)
                ).catch(() => []),
            ]);
            setTickets(ticketData);
            setAssets(assetData);
            setFidoKeys(fidoData);
        } catch {
            toast.error('Fehler beim Laden');
        } finally {
            setLoading(false);
        }
    };

    const openModal = (prefill = {}) => {
        if (formAssets.length === 0) {
            // Seed immediately from already-loaded assets, then refresh in background
            if (assets.length > 0) setFormAssets(assets);
            api.get('/assets/mine').then(r => setFormAssets(r.data.data)).catch(() => {});
        }
        const hasPrefill = Object.keys(prefill).length > 0;
        setFormData({ title: '', description: '', category: 'Allgemein', priority: 'mittel', asset_id: '', ...prefill });
        setSelectedTopic(null);
        setQuestionAnswers({});
        // Defekt melden (direkt mit Asset) → Schritt 2 (einfaches Formular), sonst Themen-Auswahl
        setWizardStep(hasPrefill ? 2 : 0);
        setShowModal(true);
    };

    const selectWizardTopic = (topic) => {
        setSelectedTopic(topic);
        // Auto-fill known answers
        const autoAnswers = {};
        const os = detectOS();
        if (os && topic.questions.find(q => q.id === 'bs')) autoAnswers['bs'] = os;
        setQuestionAnswers(autoAnswers);
        // Auto-select device if user has exactly one (assets is always loaded, formAssets may still be async)
        const autoAssetId = assets.length === 1 ? String(assets[0].id) : '';
        setFormData(f => ({ ...f, title: topic.titleTemplate, category: topic.category, priority: topic.priority, asset_id: autoAssetId || f.asset_id }));
        setWizardStep(1);
    };

    const setAnswer = (id, val) => setQuestionAnswers(prev => ({ ...prev, [id]: val }));

    const handleCreate = async (e) => {
        e.preventDefault();
        setFormLoading(true);
        try {
            const description = selectedTopic
                ? buildDescription(selectedTopic, questionAnswers)
                : formData.description;
            const ticket = await ticketService.create({
                ...formData,
                description,
                asset_id: formData.asset_id || undefined,
            });
            toast.success(`Ticket ${ticket.ticket_number} wurde erstellt`);
            setShowModal(false);
            resetForm();
            loadAll();
        } catch (err) {
            toast.error(err.message || 'Fehler beim Erstellen');
        } finally {
            setFormLoading(false);
        }
    };

    const resetForm = () => {
        setFormData({ title: '', description: '', category: 'Allgemein', priority: 'mittel', asset_id: '' });
        setWizardStep(0);
    };

    // KI-Chat auto-scroll
    useEffect(() => {
        kiBottomRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [kiMessages]);

    // KI-Chat focus when tab opens
    useEffect(() => {
        if (activeTab === 'ki') setTimeout(() => kiInputRef.current?.focus(), 100);
    }, [activeTab]);

    const sendKiMessage = async () => {
        const text = kiInput.trim();
        if (!text || kiLoading) return;
        const userMsg = { role: 'user', content: text };
        const newMsgs = [...kiMessages, userMsg];
        setKiMessages(newMsgs);
        setKiInput('');
        setKiLoading(true);
        try {
            const ctx = newMsgs.filter(m => m !== KI_WELCOME).slice(-16);
            const reply = await aiService.chat(ctx, true);
            setKiMessages(prev => [...prev, { role: 'assistant', content: reply }]);
        } catch (err) {
            setKiMessages(prev => [...prev, {
                role: 'assistant',
                content: 'Entschuldigung, ich konnte deine Anfrage gerade nicht bearbeiten. Bitte versuche es erneut oder erstelle ein Support-Ticket.',
                isError: true,
            }]);
        } finally {
            setKiLoading(false);
            setTimeout(() => kiInputRef.current?.focus(), 50);
        }
    };

    const activeTickets = tickets.filter(t => ['offen', 'in_bearbeitung', 'warten_auf_mitarbeiter', 'warten_auf_support'].includes(t.status));
    const shownTickets  = ticketFilter === 'aktiv' ? activeTickets : tickets;
    const firstName     = user?.first_name || user?.username || '';

    if (loading) return <LoadingSpinner />;

    const saveEmailNotif = async (enabled) => {
        setSavingNotif(true);
        try {
            await api.put('/auth/notifications', { email_notifications: enabled });
            setEmailNotif(enabled);
            toast.success(enabled ? 'E-Mail-Benachrichtigungen aktiviert' : 'E-Mail-Benachrichtigungen deaktiviert');
        } catch {
            toast.error('Fehler beim Speichern');
        } finally {
            setSavingNotif(false);
        }
    };

    const toggleStaffNotif = async (key) => {
        const newVal = !staffNotif[key];
        const updated = { ...staffNotif, [key]: newVal };
        setStaffNotif(updated);
        setSavingStaffNotif(true);
        try {
            await api.put('/auth/staff-notifications', updated);
            toast.success('Einstellung gespeichert');
        } catch {
            setStaffNotif(staffNotif); // revert
            toast.error('Fehler beim Speichern');
        } finally {
            setSavingStaffNotif(false);
        }
    };

    const NAV_TABS = [
        { key: 'anfragen',      label: 'Anfragen',       icon: '📋', count: tickets.length   },
        { key: 'geraete',       label: 'Meine Geräte',   icon: '💻', count: assets.length    },
        { key: 'fido',          label: 'FIDO-Keys',       icon: '🔑', count: fidoKeys.length  },
        { key: 'ki',            label: 'KI-Hilfe',        icon: '🤖', count: null             },
        { key: 'einstellungen', label: 'Einstellungen',   icon: '⚙️', count: null             },
    ];

    /* ─── Schnellzugriff-Card Helper ─── */
    const QuickCard = ({ icon, title, sub, primary, onClick, danger }) => (
        <button onClick={onClick} style={{
            display: 'flex', alignItems: 'center', gap: '12px',
            padding: '14px 20px', borderRadius: '10px', cursor: 'pointer',
            border: primary ? 'none' : '1px solid var(--border-color)',
            background: primary ? 'var(--cereda-primary)' : 'var(--bg-secondary)',
            color: primary ? '#fff' : 'var(--text-primary)',
            fontWeight: 600, fontSize: '0.875rem',
            transition: 'opacity 0.15s, border-color 0.15s, background 0.15s',
            boxShadow: primary ? '0 2px 10px rgba(0,0,0,0.15)' : 'none',
            textAlign: 'left',
        }}
            onMouseEnter={e => {
                if (primary) e.currentTarget.style.opacity = '0.88';
                else if (danger) { e.currentTarget.style.borderColor = 'var(--danger)'; e.currentTarget.style.background = 'rgba(239,68,68,0.06)'; }
                else e.currentTarget.style.borderColor = 'var(--cereda-primary)';
            }}
            onMouseLeave={e => {
                if (primary) e.currentTarget.style.opacity = '1';
                else if (danger) { e.currentTarget.style.borderColor = 'var(--border-color)'; e.currentTarget.style.background = 'var(--bg-secondary)'; }
                else e.currentTarget.style.borderColor = 'var(--border-color)';
            }}
        >
            <span style={{ fontSize: '1.25rem', flexShrink: 0 }}>{icon}</span>
            <div>
                <div>{title}</div>
                <div style={{ fontSize: '0.725rem', fontWeight: 400, opacity: primary ? 0.85 : 1, color: primary ? 'inherit' : 'var(--text-muted)', marginTop: '1px' }}>{sub}</div>
            </div>
        </button>
    );

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

                {/* ── Header ── */}
                <div style={{
                    background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                    borderRadius: '12px', padding: '20px 24px', marginBottom: '18px',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    flexWrap: 'wrap', gap: '16px',
                }}>
                    {/* Avatar + Name */}
                    <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
                        <div style={{
                            width: '52px', height: '52px', borderRadius: '50%', flexShrink: 0,
                            background: 'linear-gradient(135deg, var(--cereda-primary), var(--cereda-accent, #6366f1))',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            fontSize: '1.125rem', fontWeight: 700, color: 'white',
                        }}>
                            {firstName.split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2) || '?'}
                        </div>
                        <div>
                            <div style={{ fontWeight: 700, fontSize: '1.0625rem', color: 'var(--text-primary)' }}>
                                Hallo, {firstName}! 👋
                            </div>
                            <div style={{ fontSize: '0.8125rem', color: 'var(--text-muted)', marginTop: '2px' }}>
                                {user?.email}
                            </div>
                        </div>
                    </div>

                    {/* Klickbare Stat-Badges */}
                    <div style={{ display: 'flex', gap: '20px', flexWrap: 'wrap' }}>
                        {[
                            { value: tickets.length,       label: 'Anfragen',   color: 'var(--cereda-primary)',                                              tab: 'anfragen' },
                            { value: activeTickets.length, label: 'Aktiv',      color: activeTickets.length > 0 ? 'var(--warning)' : 'var(--success)',        tab: 'anfragen' },
                            { value: assets.length,        label: 'Geräte',     color: 'var(--text-primary)',                                                 tab: 'geraete'  },
                            { value: fidoKeys.length,      label: 'FIDO-Keys',  color: 'var(--text-primary)',                                                 tab: 'fido'     },
                        ].map(({ value, label, color, tab }) => (
                            <div key={label} style={{ textAlign: 'center', cursor: 'pointer' }}
                                onClick={() => setActiveTab(tab)}
                                title={`Zu ${label} wechseln`}>
                                <div style={{ fontSize: '1.375rem', fontWeight: 800, color }}>{value}</div>
                                <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', marginTop: '1px' }}>{label}</div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* ── Schnellzugriff ── */}
                <div style={{ marginBottom: '18px' }}>
                    <div style={{
                        fontSize: '0.7rem', fontWeight: 700, color: 'var(--text-muted)',
                        textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '10px',
                    }}>
                        ⚡ Schnellzugriff
                    </div>
                    <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                        <QuickCard
                            icon="📋" title="Neue Anfrage" sub="Support-Ticket erstellen"
                            primary onClick={() => openModal()}
                        />
                        {assets.length > 0 && (
                            <QuickCard
                                icon="🔴" title="Defekt melden" sub="Hardware-Problem melden"
                                danger onClick={() => openModal({ category: 'Hardware' })}
                            />
                        )}
                                        <QuickCard
                            icon="🤖" title="KI-Hilfe" sub="Sofort-Hilfe vom IT-Assistenten"
                            onClick={() => setActiveTab('ki')}
                        />
                    </div>
                </div>

                {/* ── Tab-Navigation ── */}
                <div style={{
                    display: 'flex', gap: '4px', marginBottom: '18px',
                    background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                    borderRadius: '10px', padding: '4px',
                }}>
                    {NAV_TABS.map(tab => (
                        <button key={tab.key} onClick={() => setActiveTab(tab.key)} style={{
                            flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
                            gap: '6px', padding: '9px 12px', borderRadius: '7px',
                            border: 'none', cursor: 'pointer', fontWeight: 600, fontSize: '0.825rem',
                            transition: 'all 0.15s',
                            background: activeTab === tab.key ? 'var(--cereda-primary)' : 'transparent',
                            color: activeTab === tab.key ? '#fff' : 'var(--text-secondary)',
                        }}>
                            <span>{tab.icon}</span>
                            <span>{tab.label}</span>
                            {tab.count !== null && (
                                <span style={{
                                    background: activeTab === tab.key ? 'rgba(255,255,255,0.22)' : 'var(--bg-tertiary)',
                                    color: activeTab === tab.key ? '#fff' : 'var(--text-muted)',
                                    borderRadius: '10px', padding: '1px 7px', fontSize: '0.7rem',
                                    minWidth: '20px', textAlign: 'center',
                                }}>{tab.count}</span>
                            )}
                        </button>
                    ))}
                </div>

                {/* ══ Tab: Anfragen ══ */}
                {activeTab === 'anfragen' && (
                    <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px', flexWrap: 'wrap', gap: '8px' }}>
                            <div style={{ fontWeight: 700, fontSize: '0.9375rem', color: 'var(--text-primary)' }}>
                                Meine Anfragen
                            </div>
                            <div style={{ display: 'flex', gap: '6px' }}>
                                {[
                                    { key: 'aktiv', label: `Aktiv (${activeTickets.length})` },
                                    { key: 'alle',  label: `Alle (${tickets.length})` },
                                ].map(f => (
                                    <button key={f.key} onClick={() => setTicketFilter(f.key)} style={{
                                        padding: '4px 14px', borderRadius: '20px', cursor: 'pointer', fontSize: '0.775rem',
                                        border: ticketFilter === f.key ? '1.5px solid var(--cereda-primary)' : '1.5px solid var(--border-color)',
                                        background: ticketFilter === f.key ? 'var(--cereda-primary)' : 'var(--bg-secondary)',
                                        color: ticketFilter === f.key ? '#fff' : 'var(--text-secondary)',
                                        fontWeight: ticketFilter === f.key ? 600 : 400,
                                    }}>{f.label}</button>
                                ))}
                            </div>
                        </div>

                        {shownTickets.length === 0 ? (
                            <div style={{
                                background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                                borderRadius: '10px', padding: '40px', textAlign: 'center',
                            }}>
                                <div style={{ fontSize: '2rem', marginBottom: '8px' }}>✅</div>
                                <div style={{ fontWeight: 600, color: 'var(--text-secondary)', marginBottom: '6px' }}>
                                    {ticketFilter === 'aktiv' ? 'Keine aktiven Anfragen' : 'Noch keine Anfragen'}
                                </div>
                                <div style={{ fontSize: '0.8125rem', color: 'var(--text-muted)', marginBottom: '16px' }}>
                                    {ticketFilter === 'aktiv' ? 'Alle deine Anfragen sind erledigt.' : 'Erstelle deine erste Support-Anfrage.'}
                                </div>
                                <button className="btn btn-primary btn-small" onClick={() => openModal()}>+ Neue Anfrage</button>
                            </div>
                        ) : (
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '12px' }}>
                                {shownTickets.map(ticket => (
                                    <TicketCard key={ticket.id} ticket={ticket}
                                        onClick={() => navigate(`/tickets/${ticket.id}`)} />
                                ))}
                            </div>
                        )}
                    </div>
                )}

                {/* ══ Tab: Geräte ══ */}
                {activeTab === 'geraete' && (
                    <div>
                        <div style={{ fontWeight: 700, fontSize: '0.9375rem', color: 'var(--text-primary)', marginBottom: '12px' }}>
                            Meine Geräte
                        </div>
                        {assets.length === 0 ? (
                            <div style={{
                                background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                                borderRadius: '10px', padding: '40px', textAlign: 'center',
                            }}>
                                <div style={{ fontSize: '2rem', marginBottom: '8px' }}>💻</div>
                                <div style={{ fontWeight: 600, color: 'var(--text-secondary)', marginBottom: '4px' }}>Keine Geräte zugewiesen</div>
                                <div style={{ fontSize: '0.8125rem', color: 'var(--text-muted)' }}>
                                    Wende dich an den IT-Support falls hier Geräte fehlen.
                                </div>
                            </div>
                        ) : (
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: '12px' }}>
                                {assets.map(asset => (
                                    <div key={asset.id} style={{
                                        background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                                        borderRadius: '10px', padding: '16px',
                                        display: 'flex', flexDirection: 'column', gap: '12px',
                                    }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                            <div style={{
                                                width: '44px', height: '44px', borderRadius: '8px', flexShrink: 0,
                                                background: 'var(--bg-tertiary)', border: '1px solid var(--border-color)',
                                                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.25rem',
                                            }}>
                                                {ASSET_TYPE_ICONS[asset.type] || '📦'}
                                            </div>
                                            <div style={{ flex: 1, minWidth: 0 }}>
                                                <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                                    {asset.name}
                                                </div>
                                                <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '2px' }}>
                                                    {asset.type}{asset.model ? ` · ${asset.model}` : ''}
                                                </div>
                                                {asset.serial_number && (
                                                    <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', fontFamily: 'monospace', marginTop: '2px' }}>
                                                        S/N: {asset.serial_number}
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                        <button
                                            className="btn btn-danger btn-small"
                                            style={{ width: '100%', fontSize: '0.775rem' }}
                                            onClick={() => openModal({ category: 'Hardware', asset_id: String(asset.id) })}
                                        >
                                            🔴 Defekt melden
                                        </button>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                )}

                {/* ══ Tab: FIDO-Keys ══ */}
                {activeTab === 'fido' && (
                    <div>
                        <div style={{ fontWeight: 700, fontSize: '0.9375rem', color: 'var(--text-primary)', marginBottom: '12px' }}>
                            Meine FIDO-Keys
                        </div>
                        {fidoKeys.length === 0 ? (
                            <div style={{
                                background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                                borderRadius: '10px', padding: '40px', textAlign: 'center',
                            }}>
                                <div style={{ fontSize: '2rem', marginBottom: '8px' }}>🔑</div>
                                <div style={{ fontWeight: 600, color: 'var(--text-secondary)', marginBottom: '4px' }}>Keine FIDO-Keys zugewiesen</div>
                                <div style={{ fontSize: '0.8125rem', color: 'var(--text-muted)' }}>
                                    Wende dich an den IT-Support um einen FIDO-Key zu erhalten.
                                </div>
                            </div>
                        ) : (
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: '12px' }}>
                                {fidoKeys.map(key => {
                                    const statusConf = FIDO_STATUS[key.status] || {};
                                    return (
                                        <div key={key.id} style={{
                                            background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                                            borderRadius: '10px', padding: '16px',
                                            display: 'flex', alignItems: 'center', gap: '14px',
                                        }}>
                                            <div style={{
                                                width: '44px', height: '44px', borderRadius: '8px', flexShrink: 0,
                                                background: 'var(--bg-tertiary)', border: '1px solid var(--border-color)',
                                                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.25rem',
                                            }}>
                                                🔑
                                            </div>
                                            <div style={{ flex: 1, minWidth: 0 }}>
                                                <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                                    {key.label || key.serial_number}
                                                </div>
                                                <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '2px', fontFamily: 'monospace' }}>
                                                    {key.serial_number}
                                                </div>
                                                <div style={{ marginTop: '6px' }}>
                                                    <span className={`status-badge ${statusConf.css}`} style={{ fontSize: '0.65rem' }}>
                                                        {statusConf.label}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                )}

                {/* ══ Tab: KI-Hilfe ══ */}
                {activeTab === 'ki' && (
                    <div style={{ display: 'flex', flexDirection: 'column', height: '520px' }}>
                        {/* Chat-Header */}
                        <div style={{
                            background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                            borderRadius: '10px 10px 0 0', padding: '14px 18px',
                            display: 'flex', alignItems: 'center', gap: '10px',
                        }}>
                            <span style={{ fontSize: '1.375rem' }}>🤖</span>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 700, fontSize: '0.9375rem', color: '#fff' }}>IT-Assistent</div>
                                <div style={{ fontSize: '0.75rem', color: 'rgba(255,255,255,0.8)' }}>
                                    Ich helfe dir bei IT-Problemen – rund um die Uhr
                                </div>
                            </div>
                            <button
                                onClick={() => setKiMessages([KI_WELCOME])}
                                title="Chat zurücksetzen"
                                style={{
                                    background: 'rgba(255,255,255,0.2)', border: 'none', color: '#fff',
                                    borderRadius: '6px', padding: '4px 10px', fontSize: '0.75rem', cursor: 'pointer',
                                }}
                            >
                                Leeren
                            </button>
                        </div>

                        {/* Nachrichten */}
                        <div style={{
                            flex: 1, overflowY: 'auto', padding: '14px 16px',
                            background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                            borderTop: 'none', display: 'flex', flexDirection: 'column', gap: '10px',
                        }}>
                            {kiMessages.map((msg, i) => (
                                <div key={i} style={{ display: 'flex', justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start' }}>
                                    {msg.role === 'assistant' && (
                                        <div style={{
                                            width: '28px', height: '28px', borderRadius: '50%', flexShrink: 0,
                                            background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                                            fontSize: '0.875rem', marginRight: '8px', alignSelf: 'flex-end',
                                        }}>🤖</div>
                                    )}
                                    <div style={{
                                        maxWidth: '80%', padding: '9px 13px', fontSize: '0.875rem', lineHeight: 1.55,
                                        borderRadius: msg.role === 'user' ? '14px 14px 3px 14px' : '14px 14px 14px 3px',
                                        background: msg.role === 'user'
                                            ? 'linear-gradient(135deg, #6366f1, #8b5cf6)'
                                            : msg.isError ? '#fee2e2' : 'var(--bg-primary)',
                                        color: msg.role === 'user' ? '#fff' : msg.isError ? '#991b1b' : 'var(--text-primary)',
                                        border: msg.role === 'user' ? 'none' : '1px solid var(--border-color)',
                                        wordBreak: 'break-word',
                                    }}>
                                        {msg.role === 'assistant'
                                            ? <div className="md-content" dangerouslySetInnerHTML={renderMd(msg.content)} />
                                            : msg.content}
                                        {/* Ticket erstellen Button nach KI-Empfehlung */}
                                        {msg.role === 'assistant' && msg.content.toLowerCase().includes('ticket') && i > 0 && (
                                            <div style={{ marginTop: '8px' }}>
                                                <button
                                                    onClick={() => openModal()}
                                                    style={{
                                                        background: 'var(--cereda-primary)', color: '#fff',
                                                        border: 'none', borderRadius: '6px', padding: '5px 12px',
                                                        fontSize: '0.775rem', fontWeight: 600, cursor: 'pointer',
                                                    }}
                                                >
                                                    + Ticket erstellen
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            ))}
                            {kiLoading && (
                                <div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px' }}>
                                    <div style={{
                                        width: '28px', height: '28px', borderRadius: '50%',
                                        background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                                        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '0.875rem',
                                    }}>🤖</div>
                                    <div style={{
                                        padding: '10px 14px', borderRadius: '14px 14px 14px 3px',
                                        background: 'var(--bg-primary)', border: '1px solid var(--border-color)',
                                        fontSize: '1.125rem', letterSpacing: '2px',
                                    }}>
                                        <span style={{ animation: 'pulse 1.2s infinite' }}>●</span>
                                        <span style={{ animation: 'pulse 1.2s 0.3s infinite', opacity: 0.5 }}>●</span>
                                        <span style={{ animation: 'pulse 1.2s 0.6s infinite', opacity: 0.25 }}>●</span>
                                    </div>
                                </div>
                            )}
                            <div ref={kiBottomRef} />
                        </div>

                        {/* Eingabe */}
                        <div style={{
                            borderRadius: '0 0 10px 10px', padding: '10px 12px',
                            background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                            borderTop: 'none', display: 'flex', gap: '8px',
                        }}>
                            <textarea
                                ref={kiInputRef}
                                value={kiInput}
                                onChange={e => setKiInput(e.target.value)}
                                onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendKiMessage(); } }}
                                placeholder="Beschreibe dein Problem… (Enter zum Senden)"
                                disabled={kiLoading}
                                rows={2}
                                style={{
                                    flex: 1, resize: 'none', padding: '8px 10px', borderRadius: '8px',
                                    border: '1px solid var(--border-color)', fontSize: '0.875rem',
                                    background: 'var(--bg-primary)', color: 'var(--text-primary)', outline: 'none',
                                    fontFamily: 'inherit',
                                }}
                            />
                            <button
                                onClick={sendKiMessage}
                                disabled={kiLoading || !kiInput.trim()}
                                style={{
                                    padding: '0 16px', borderRadius: '8px', border: 'none', height: '52px',
                                    background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                                    color: '#fff', fontSize: '1.125rem', cursor: 'pointer',
                                    opacity: kiLoading || !kiInput.trim() ? 0.5 : 1,
                                    alignSelf: 'flex-end',
                                }}
                            >↑</button>
                        </div>
                    </div>
                )}

                {/* ══ Tab: Einstellungen ══ */}
                {activeTab === 'einstellungen' && (
                    <div style={{ maxWidth: '560px' }}>
                        <div style={{ fontWeight: 700, fontSize: '0.9375rem', color: 'var(--text-primary)', marginBottom: '16px' }}>
                            Einstellungen
                        </div>

                        {/* E-Mail-Benachrichtigungen (Mitarbeiter) */}
                        {!isStaff && (
                        <div style={{
                            background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                            borderRadius: '10px', padding: '20px',
                        }}>
                            <div style={{ fontWeight: 700, fontSize: '0.875rem', color: 'var(--text-primary)', marginBottom: '16px' }}>
                                📧 E-Mail-Benachrichtigungen
                            </div>

                            {/* Hauptschalter */}
                            <div style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                padding: '14px 16px', borderRadius: '8px',
                                background: 'var(--bg-primary)', border: '1px solid var(--border-color)',
                                marginBottom: '12px',
                            }}>
                                <div>
                                    <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text-primary)' }}>
                                        E-Mail-Benachrichtigungen aktivieren
                                    </div>
                                    <div style={{ fontSize: '0.775rem', color: 'var(--text-muted)', marginTop: '3px' }}>
                                        Erhalte E-Mails bei Aktualisierungen deiner IT-Anfragen
                                    </div>
                                </div>
                                <button
                                    disabled={savingNotif}
                                    onClick={() => saveEmailNotif(!emailNotif)}
                                    style={{
                                        width: '44px', height: '24px', borderRadius: '12px', border: 'none',
                                        background: emailNotif ? 'var(--cereda-primary)' : 'var(--border-color)',
                                        cursor: savingNotif ? 'not-allowed' : 'pointer',
                                        position: 'relative', transition: 'background 0.2s', flexShrink: 0,
                                        opacity: savingNotif ? 0.6 : 1,
                                    }}
                                    title={emailNotif ? 'Deaktivieren' : 'Aktivieren'}
                                >
                                    <span style={{
                                        position: 'absolute', top: '3px',
                                        left: emailNotif ? '22px' : '3px',
                                        width: '18px', height: '18px', borderRadius: '50%',
                                        background: '#fff', transition: 'left 0.2s',
                                        boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
                                    }} />
                                </button>
                            </div>

                            {/* Info-Kasten: welche Mails */}
                            <div style={{
                                padding: '12px 14px', borderRadius: '8px',
                                background: emailNotif ? 'rgba(59,130,246,0.06)' : 'var(--bg-tertiary)',
                                border: `1px solid ${emailNotif ? 'rgba(59,130,246,0.2)' : 'var(--border-color)'}`,
                            }}>
                                <div style={{ fontSize: '0.775rem', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: emailNotif ? '8px' : 0 }}>
                                    {emailNotif ? 'Du erhältst E-Mails bei:' : 'Du erhältst derzeit keine E-Mails.'}
                                </div>
                                {emailNotif && (
                                    <ul style={{ margin: 0, paddingLeft: '16px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
                                        {[
                                            'Bestätigung wenn du eine neue Anfrage erstellst',
                                            'Neue Kommentare des IT-Supports auf deine Anfragen',
                                            'Statusänderungen deiner Anfragen (z.B. „In Bearbeitung", „Gelöst")',
                                            'Zufriedenheits-Umfrage nach Abschluss einer Anfrage',
                                        ].map(text => (
                                            <li key={text} style={{ fontSize: '0.775rem', color: 'var(--text-muted)' }}>{text}</li>
                                        ))}
                                    </ul>
                                )}
                            </div>
                        </div>
                        )}

                        {/* E-Mail-Benachrichtigungen (Staff) */}
                        {isStaff && (
                        <div style={{
                            background: 'var(--bg-secondary)', border: '1px solid var(--border-color)',
                            borderRadius: '10px', padding: '20px',
                        }}>
                            <div style={{ fontWeight: 700, fontSize: '0.875rem', color: 'var(--text-primary)', marginBottom: '4px' }}>
                                📧 E-Mail-Benachrichtigungen
                            </div>
                            <div style={{ fontSize: '0.775rem', color: 'var(--text-muted)', marginBottom: '16px' }}>
                                Wähle für welche Ereignisse du E-Mails erhalten möchtest.
                            </div>

                            {[
                                { key: 'notif_ticket_created',  label: 'Neues Ticket eingegangen',   desc: 'Wenn ein neues Ticket im System erstellt wird' },
                                { key: 'notif_ticket_assigned', label: 'Ticket zugewiesen',           desc: 'Wenn dir ein Ticket zugewiesen wird' },
                                { key: 'notif_new_comment',     label: 'Neue Antwort auf Ticket',     desc: 'Wenn ein Mitarbeiter auf ein dir zugewiesenes Ticket antwortet' },
                                { key: 'notif_weekly_report',   label: 'Wöchentlicher Report',        desc: 'Montags: Zusammenfassung offener und geschlossener Tickets' },
                            ].map(({ key, label, desc }) => (
                                <div key={key} style={{
                                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                    padding: '14px 16px', borderRadius: '8px',
                                    background: 'var(--bg-primary)', border: '1px solid var(--border-color)',
                                    marginBottom: '8px',
                                }}>
                                    <div>
                                        <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text-primary)' }}>{label}</div>
                                        <div style={{ fontSize: '0.775rem', color: 'var(--text-muted)', marginTop: '3px' }}>{desc}</div>
                                    </div>
                                    <button
                                        disabled={savingStaffNotif}
                                        onClick={() => toggleStaffNotif(key)}
                                        style={{
                                            width: '44px', height: '24px', borderRadius: '12px', border: 'none',
                                            background: staffNotif[key] ? 'var(--cereda-primary)' : 'var(--border-color)',
                                            cursor: savingStaffNotif ? 'not-allowed' : 'pointer',
                                            position: 'relative', transition: 'background 0.2s', flexShrink: 0,
                                            opacity: savingStaffNotif ? 0.6 : 1,
                                        }}
                                    >
                                        <span style={{
                                            position: 'absolute', top: '3px',
                                            left: staffNotif[key] ? '22px' : '3px',
                                            width: '18px', height: '18px', borderRadius: '50%',
                                            background: '#fff', transition: 'left 0.2s',
                                            boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
                                        }} />
                                    </button>
                                </div>
                            ))}
                        </div>
                        )}
                    </div>
                )}

            </div>

            {/* ── Modal: Klick-Assistent ── */}
            {showModal && (
                <div className="modal-overlay" onClick={() => { setShowModal(false); resetForm(); }}>
                    <div className="modal-content modal-large" onClick={e => e.stopPropagation()}>

                        {/* ─── Schritt 0: Thema wählen ─── */}
                        {wizardStep === 0 && (
                            <>
                                <div className="modal-header">
                                    <div>
                                        <h2 className="modal-title">Was kann ich für dich tun? 🙋</h2>
                                        <p style={{ margin: '4px 0 0', fontSize: '0.8125rem', color: 'var(--text-muted)' }}>
                                            Klick auf dein Problem – wir füllen alles vor.
                                        </p>
                                    </div>
                                    <button className="modal-close" onClick={() => { setShowModal(false); resetForm(); }}>×</button>
                                </div>

                                <div style={{
                                    display: 'grid',
                                    gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
                                    gap: '10px', padding: '4px 0 16px',
                                }}>
                                    {WIZARD_TOPICS.map(topic => (
                                        <button
                                            key={topic.key}
                                            onClick={() => selectWizardTopic(topic)}
                                            style={{
                                                display: 'flex', flexDirection: 'column', alignItems: 'flex-start',
                                                gap: '6px', padding: '16px', borderRadius: '10px', cursor: 'pointer',
                                                border: '1.5px solid var(--border-color)',
                                                background: 'var(--bg-secondary)',
                                                textAlign: 'left', transition: 'all 0.15s',
                                            }}
                                            onMouseEnter={e => {
                                                e.currentTarget.style.borderColor = 'var(--cereda-primary)';
                                                e.currentTarget.style.background = 'rgba(99,102,241,0.06)';
                                                e.currentTarget.style.transform = 'translateY(-2px)';
                                            }}
                                            onMouseLeave={e => {
                                                e.currentTarget.style.borderColor = 'var(--border-color)';
                                                e.currentTarget.style.background = 'var(--bg-secondary)';
                                                e.currentTarget.style.transform = 'translateY(0)';
                                            }}
                                        >
                                            <span style={{ fontSize: '1.75rem' }}>{topic.icon}</span>
                                            <div style={{ fontWeight: 700, fontSize: '0.875rem', color: 'var(--text-primary)' }}>
                                                {topic.label}
                                            </div>
                                            <div style={{ fontSize: '0.725rem', color: 'var(--text-muted)', lineHeight: 1.4 }}>
                                                {topic.sub}
                                            </div>
                                        </button>
                                    ))}
                                </div>
                            </>
                        )}

                        {/* ─── Schritt 1: Strukturierte Fragen zum gewählten Thema ─── */}
                        {wizardStep === 1 && selectedTopic && (
                            <>
                                <div className="modal-header">
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                        <button
                                            onClick={() => setWizardStep(0)}
                                            style={{
                                                background: 'none', border: '1px solid var(--border-color)',
                                                borderRadius: '6px', padding: '4px 10px', cursor: 'pointer',
                                                fontSize: '0.875rem', color: 'var(--text-secondary)',
                                            }}
                                        >← Zurück</button>
                                        <h2 className="modal-title" style={{ margin: 0 }}>
                                            {selectedTopic.icon} {selectedTopic.label}
                                        </h2>
                                    </div>
                                    <button className="modal-close" onClick={() => { setShowModal(false); resetForm(); }}>×</button>
                                </div>

                                <form onSubmit={handleCreate}>
                                    {selectedTopic.questions.map((q, idx) => (
                                        <div className="form-group" key={q.id}>
                                            <label className="form-label">{q.label}{q.required ? ' *' : ''}</label>
                                            {q.type === 'textarea' ? (
                                                <textarea
                                                    className="form-textarea" rows={3}
                                                    required={q.required}
                                                    autoFocus={idx === 0}
                                                    value={questionAnswers[q.id] || ''}
                                                    onChange={e => setAnswer(q.id, e.target.value)}
                                                    placeholder={q.placeholder}
                                                />
                                            ) : (
                                                <input
                                                    type="text" className="form-input"
                                                    required={q.required}
                                                    autoFocus={idx === 0}
                                                    value={questionAnswers[q.id] || ''}
                                                    onChange={e => setAnswer(q.id, e.target.value)}
                                                    placeholder={q.placeholder}
                                                />
                                            )}
                                        </div>
                                    ))}

                                    <div className="form-group">
                                        <label className="form-label">Betreff</label>
                                        <input type="text" className="form-input" required
                                            value={formData.title}
                                            onChange={e => setFormData({ ...formData, title: e.target.value })}
                                            placeholder='Kurzer Betreff für dein Ticket' />
                                    </div>

                                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                                        <div className="form-group" style={{ marginBottom: 0 }}>
                                            <label className="form-label">Bereich</label>
                                            <select className="form-select" value={formData.category}
                                                onChange={e => setFormData({ ...formData, category: e.target.value })}>
                                                {categories.map(c => <option key={c.id} value={c.name}>{c.icon} {c.name}</option>)}
                                            </select>
                                        </div>
                                        <div className="form-group" style={{ marginBottom: 0 }}>
                                            <label className="form-label">Dringlichkeit</label>
                                            <select className="form-select" value={formData.priority}
                                                onChange={e => setFormData({ ...formData, priority: e.target.value })}>
                                                <option value="niedrig">🟢 Niedrig – kann warten</option>
                                                <option value="mittel">🔵 Mittel – bald bitte</option>
                                                <option value="hoch">🟠 Hoch – dringend</option>
                                                <option value="kritisch">🔴 Kritisch – ich kann nicht arbeiten</option>
                                            </select>
                                        </div>
                                    </div>

                                    {formAssets.length > 0 && (
                                        <div className="form-group">
                                            <label className="form-label">Betroffenes Gerät (optional)</label>
                                            <select className="form-select" value={formData.asset_id}
                                                onChange={e => setFormData({ ...formData, asset_id: e.target.value })}>
                                                <option value="">— Kein Gerät ausgewählt</option>
                                                {formAssets.map(a => (
                                                    <option key={a.id} value={a.id}>{a.name} ({a.type})</option>
                                                ))}
                                            </select>
                                        </div>
                                    )}

                                    <div className="card-footer">
                                        <button type="button" className="btn btn-secondary"
                                            onClick={() => { setShowModal(false); resetForm(); }} disabled={formLoading}>
                                            Abbrechen
                                        </button>
                                        <button type="submit" className="btn btn-primary" disabled={formLoading}>
                                            {formLoading ? 'Wird gesendet…' : '📨 Absenden'}
                                        </button>
                                    </div>
                                </form>
                            </>
                        )}

                        {/* ─── Schritt 2: Einfaches Defekt-Formular (direkt aus Geräte-Tab) ─── */}
                        {wizardStep === 2 && (
                            <>
                                <div className="modal-header">
                                    <div>
                                        <h2 className="modal-title">🔴 Defekt melden</h2>
                                        <p style={{ margin: '4px 0 0', fontSize: '0.8125rem', color: 'var(--text-muted)' }}>
                                            Beschreibe das Hardware-Problem so genau wie möglich.
                                        </p>
                                    </div>
                                    <button className="modal-close" onClick={() => { setShowModal(false); resetForm(); }}>×</button>
                                </div>

                                <form onSubmit={handleCreate}>
                                    <div className="form-group">
                                        <label className="form-label">Was ist das Problem? *</label>
                                        <input type="text" className="form-input" required autoFocus
                                            value={formData.title}
                                            onChange={e => setFormData({ ...formData, title: e.target.value })}
                                            placeholder='z.B. "Bildschirm zeigt nichts", "Laptop startet nicht"' />
                                    </div>

                                    <div className="form-group">
                                        <label className="form-label">Beschreibung</label>
                                        <textarea className="form-textarea" rows={4}
                                            value={formData.description}
                                            onChange={e => setFormData({ ...formData, description: e.target.value })}
                                            placeholder="Was ist genau passiert? Wann? Fehlermeldungen?" />
                                    </div>

                                    <div className="form-group">
                                        <label className="form-label">Dringlichkeit</label>
                                        <select className="form-select" value={formData.priority}
                                            onChange={e => setFormData({ ...formData, priority: e.target.value })}>
                                            <option value="niedrig">🟢 Niedrig – kann warten</option>
                                            <option value="mittel">🔵 Mittel – bald bitte</option>
                                            <option value="hoch">🟠 Hoch – dringend</option>
                                            <option value="kritisch">🔴 Kritisch – ich kann nicht arbeiten</option>
                                        </select>
                                    </div>

                                    {formAssets.length > 0 && (
                                        <div className="form-group">
                                            <label className="form-label">Betroffenes Gerät</label>
                                            <select className="form-select" value={formData.asset_id}
                                                onChange={e => setFormData({ ...formData, asset_id: e.target.value })}>
                                                <option value="">— Kein Gerät ausgewählt</option>
                                                {formAssets.map(a => (
                                                    <option key={a.id} value={a.id}>{a.name} ({a.type})</option>
                                                ))}
                                            </select>
                                        </div>
                                    )}

                                    <div className="card-footer">
                                        <button type="button" className="btn btn-secondary"
                                            onClick={() => { setShowModal(false); resetForm(); }} disabled={formLoading}>
                                            Abbrechen
                                        </button>
                                        <button type="submit" className="btn btn-primary" disabled={formLoading}>
                                            {formLoading ? 'Wird gesendet…' : '📨 Absenden'}
                                        </button>
                                    </div>
                                </form>
                            </>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
};

export default UserPortalPage;
