<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}van Hees-Theyssen-Vogel'sche Stiftung{% endblock %}</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <!-- Custom CSS - Vision 2026 Sidebar Theme -->
    <style>
        /* British Racing Green Color Palette */
        :root {
            --racing-green: #004225;
            --racing-green-light: #006837;
            --racing-green-dark: #002818;
            --grey-light: #f8f9fa;
            --grey-medium: #6c757d;
            --grey-dark: #495057;
            --orange-accent: #fd7e14;
            --orange-light: #ff922b;
            --orange-dark: #e8590c;
            --sidebar-width: 260px;
            --sidebar-collapsed-width: 64px;
            --topbar-height: 56px;
        }

        /* Global Typography */
        html {
            font-size: 15px;
        }

        body {
            font-size: 0.875rem;
            line-height: 1.4;
            font-weight: 400;
            background-color: #f0f2f5;
            overflow-x: hidden;
        }

        .h1, .h2, .h3, .h4, .h5, .h6,
        h1, h2, h3, h4, h5, h6 {
            font-weight: 600;
            line-height: 1.3;
            margin-bottom: 0.75rem;
        }

        .h1, h1 { font-size: 2rem; }
        .h2, h2 { font-size: 1.65rem; }
        .h3, h3 { font-size: 1.4rem; }
        .h4, h4 { font-size: 1.15rem; }
        .h5, h5 { font-size: 1rem; }
        .h6, h6 { font-size: 0.875rem; }

        /* ============ SIDEBAR ============ */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: var(--sidebar-width);
            background: linear-gradient(180deg, var(--racing-green-dark) 0%, var(--racing-green) 100%);
            z-index: 1040;
            overflow-y: auto;
            overflow-x: hidden;
            transition: width 0.2s ease;
            scrollbar-width: thin;
            scrollbar-color: rgba(255,255,255,0.2) transparent;
        }

        .sidebar::-webkit-scrollbar {
            width: 4px;
        }
        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255,255,255,0.2);
            border-radius: 2px;
        }

        .sidebar-brand {
            display: flex;
            align-items: center;
            padding: 1rem 1rem;
            color: white;
            text-decoration: none;
            font-weight: 700;
            font-size: 0.95rem;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            min-height: var(--topbar-height);
        }

        .sidebar-brand:hover {
            color: var(--orange-light);
        }

        .sidebar-brand i {
            font-size: 1.25rem;
            margin-right: 0.75rem;
            flex-shrink: 0;
        }

        .sidebar-section {
            padding: 0.5rem 0;
            border-bottom: 1px solid rgba(255,255,255,0.06);
        }

        .sidebar-heading {
            font-size: 0.65rem;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: rgba(255,255,255,0.4);
            padding: 0.75rem 1rem 0.25rem;
            font-weight: 600;
        }

        .sidebar-link {
            display: flex;
            align-items: center;
            padding: 0.5rem 1rem;
            color: rgba(255,255,255,0.75);
            text-decoration: none;
            font-size: 0.8rem;
            transition: all 0.15s;
            border-left: 3px solid transparent;
        }

        .sidebar-link:hover {
            color: white;
            background: rgba(255,255,255,0.08);
            border-left-color: var(--orange-accent);
        }

        .sidebar-link.active {
            color: white;
            background: rgba(255,255,255,0.12);
            border-left-color: var(--orange-accent);
        }

        .sidebar-link i {
            width: 1.25rem;
            text-align: center;
            margin-right: 0.75rem;
            font-size: 0.85rem;
            flex-shrink: 0;
        }

        .sidebar-link .badge {
            margin-left: auto;
            font-size: 0.65rem;
        }

        /* ============ TOPBAR ============ */
        .topbar {
            position: fixed;
            top: 0;
            left: var(--sidebar-width);
            right: 0;
            height: var(--topbar-height);
            background: white;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            align-items: center;
            padding: 0 1.5rem;
            z-index: 1030;
            transition: left 0.2s ease;
        }

        .topbar-toggle {
            background: none;
            border: none;
            color: var(--grey-dark);
            font-size: 1.1rem;
            cursor: pointer;
            padding: 0.25rem 0.5rem;
            margin-right: 1rem;
            border-radius: 0.25rem;
        }

        .topbar-toggle:hover {
            background: var(--grey-light);
        }

        .topbar-breadcrumb {
            font-size: 0.85rem;
            color: var(--grey-medium);
        }

        .topbar-breadcrumb a {
            color: var(--racing-green);
            text-decoration: none;
        }

        .topbar-breadcrumb a:hover {
            text-decoration: underline;
        }

        .topbar-actions {
            margin-left: auto;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        /* ============ MAIN CONTENT ============ */
        .main-content {
            margin-left: var(--sidebar-width);
            padding-top: var(--topbar-height);
            min-height: 100vh;
            transition: margin-left 0.2s ease;
        }

        .content-wrapper {
            padding: 1.25rem 1.5rem;
            max-width: 1600px;
        }

        /* ============ SIDEBAR COLLAPSED ============ */
        body.sidebar-collapsed .sidebar {
            width: var(--sidebar-collapsed-width);
        }

        body.sidebar-collapsed .sidebar .sidebar-brand span,
        body.sidebar-collapsed .sidebar .sidebar-heading,
        body.sidebar-collapsed .sidebar .sidebar-link span,
        body.sidebar-collapsed .sidebar .sidebar-link .badge {
            display: none;
        }

        body.sidebar-collapsed .sidebar .sidebar-brand i {
            margin-right: 0;
        }

        body.sidebar-collapsed .sidebar .sidebar-link {
            justify-content: center;
            padding: 0.6rem;
            border-left: none;
        }

        body.sidebar-collapsed .sidebar .sidebar-link i {
            margin-right: 0;
            font-size: 1rem;
        }

        body.sidebar-collapsed .topbar {
            left: var(--sidebar-collapsed-width);
        }

        body.sidebar-collapsed .main-content {
            margin-left: var(--sidebar-collapsed-width);
        }

        /* ============ MOBILE ============ */
        @media (max-width: 991.98px) {
            .sidebar {
                transform: translateX(-100%);
                width: var(--sidebar-width);
            }

            body.sidebar-open .sidebar {
                transform: translateX(0);
            }

            body.sidebar-open .sidebar-overlay {
                display: block;
            }

            .sidebar-overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0,0,0,0.4);
                z-index: 1035;
            }

            .topbar {
                left: 0;
            }

            .main-content {
                margin-left: 0;
            }

            body.sidebar-collapsed .topbar {
                left: 0;
            }

            body.sidebar-collapsed .main-content {
                margin-left: 0;
            }
        }

        /* ============ CARDS ============ */
        .card {
            border: 1px solid #e9ecef;
            box-shadow: 0 0.125rem 0.5rem rgba(0, 66, 37, 0.06);
            margin-bottom: 0.75rem;
            border-radius: 0.5rem;
        }

        .card-body {
            padding: 0.75rem;
        }

        .card-header {
            background-color: var(--grey-light);
            border-bottom: 1px solid #dee2e6;
            color: var(--racing-green-dark);
            padding: 0.5rem 0.75rem;
            font-size: 0.875rem;
            font-weight: 600;
        }

        .card-header.bg-primary {
            background-color: var(--racing-green) !important;
            color: white;
        }

        .card-header.bg-success {
            background-color: var(--racing-green-light) !important;
            color: white;
        }

        .card-header.bg-info {
            background-color: var(--grey-medium) !important;
            color: white;
        }

        .card-header.bg-warning {
            background-color: var(--orange-accent) !important;
            color: white;
        }

        .card-title {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 0;
        }

        .border-left-primary { border-left: 0.25rem solid var(--racing-green) !important; }
        .border-left-success { border-left: 0.25rem solid var(--racing-green-light) !important; }
        .border-left-info { border-left: 0.25rem solid var(--grey-medium) !important; }
        .border-left-warning { border-left: 0.25rem solid var(--orange-accent) !important; }
        .border-left-danger { border-left: 0.25rem solid #dc3545 !important; }

        /* ============ TABLES ============ */
        .table {
            font-size: 0.85rem;
            margin-bottom: 0.75rem;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: var(--racing-green-dark);
            background-color: var(--grey-light);
            padding: 0.5rem;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }

        .table td {
            padding: 0.5rem;
            border-top: 1px solid #dee2e6;
        }

        .table-sm th, .table-sm td {
            padding: 0.375rem;
        }

        /* ============ BUTTONS ============ */
        .btn {
            font-size: 0.8rem;
            padding: 0.375rem 0.75rem;
            border-radius: 0.25rem;
            font-weight: 500;
            line-height: 1.3;
        }

        .btn-sm {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }

        .btn-lg {
            font-size: 0.9rem;
            padding: 0.5rem 1rem;
        }

        .btn-primary { background-color: var(--racing-green); border-color: var(--racing-green); }
        .btn-primary:hover { background-color: var(--racing-green-dark); border-color: var(--racing-green-dark); }
        .btn-success { background-color: var(--racing-green-light); border-color: var(--racing-green-light); }
        .btn-success:hover { background-color: var(--racing-green); border-color: var(--racing-green); }
        .btn-warning { background-color: var(--orange-accent); border-color: var(--orange-accent); color: white; }
        .btn-warning:hover { background-color: var(--orange-dark); border-color: var(--orange-dark); color: white; }
        .btn-outline-primary { color: var(--racing-green); border-color: var(--racing-green); }
        .btn-outline-primary:hover { background-color: var(--racing-green); border-color: var(--racing-green); }
        .btn-accent { background-color: var(--orange-accent); border-color: var(--orange-accent); color: white; }
        .btn-accent:hover { background-color: var(--orange-dark); border-color: var(--orange-dark); color: white; }

        /* ============ FORMS ============ */
        .form-control, .form-select {
            font-size: 0.8rem;
            padding: 0.375rem 0.5rem;
            line-height: 1.3;
        }
        .form-control-sm, .form-select-sm {
            font-size: 0.75rem;
            padding: 0.25rem 0.375rem;
        }
        .form-label {
            font-size: 0.8rem;
            font-weight: 500;
            margin-bottom: 0.25rem;
        }
        .form-text {
            font-size: 0.7rem;
            margin-top: 0.15rem;
        }
        .form-control:focus, .form-select:focus {
            border-color: var(--racing-green-light);
            box-shadow: 0 0 0 0.15rem rgba(0, 66, 37, 0.25);
        }

        /* ============ BADGES ============ */
        .badge {
            font-size: 0.7rem;
            padding: 0.25em 0.5em;
            font-weight: 500;
        }
        .badge.bg-primary { background-color: var(--racing-green) !important; }
        .badge.bg-success { background-color: var(--racing-green-light) !important; }
        .badge.bg-warning { background-color: var(--orange-accent) !important; color: white; }
        .badge.bg-info { background-color: var(--grey-medium) !important; }

        /* ============ ALERTS ============ */
        .alert {
            padding: 0.5rem 0.75rem;
            margin-bottom: 0.75rem;
            font-size: 0.8rem;
        }
        .alert-success { background-color: rgba(0,104,55,0.1); border-color: var(--racing-green-light); color: var(--racing-green-dark); }
        .alert-warning { background-color: rgba(253,126,20,0.1); border-color: var(--orange-accent); color: var(--orange-dark); }

        /* ============ PAGINATION ============ */
        .pagination .page-link { color: var(--racing-green); font-size: 0.8rem; padding: 0.375rem 0.5rem; }
        .pagination .page-item.active .page-link { background-color: var(--racing-green); border-color: var(--racing-green); }

        /* ============ PROGRESS ============ */
        .progress { height: 1rem; font-size: 0.65rem; }

        /* ============ TEXT ============ */
        .text-primary { color: var(--racing-green) !important; }
        .text-success { color: var(--racing-green-light) !important; }
        .bg-accent { background-color: var(--orange-accent) !important; color: white; }

        /* ============ FOOTER ============ */
        .main-footer {
            padding: 0.75rem 1.5rem;
            font-size: 0.75rem;
            color: var(--grey-medium);
            border-top: 1px solid #dee2e6;
            background: white;
            text-align: center;
        }

        /* ============ DASHBOARD WIDGETS ============ */
        .stat-card {
            border-radius: 0.5rem;
            border: none;
            box-shadow: 0 0.125rem 0.5rem rgba(0,0,0,0.06);
        }

        .stat-card .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            color: white;
        }

        .stat-card .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            line-height: 1.2;
            color: var(--grey-dark);
        }

        .stat-card .stat-label {
            font-size: 0.75rem;
            color: var(--grey-medium);
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }

        .action-list .action-item {
            display: flex;
            align-items: center;
            padding: 0.6rem 0.75rem;
            border-bottom: 1px solid #f0f0f0;
            text-decoration: none;
            color: inherit;
            transition: background 0.15s;
        }

        .action-list .action-item:last-child {
            border-bottom: none;
        }

        .action-list .action-item:hover {
            background: var(--grey-light);
        }

        .action-list .action-icon {
            width: 32px;
            height: 32px;
            border-radius: 0.375rem;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            margin-right: 0.75rem;
            flex-shrink: 0;
        }

        .action-list .action-text {
            flex-grow: 1;
        }

        .action-list .action-title {
            font-size: 0.8rem;
            font-weight: 500;
        }

        .action-list .action-desc {
            font-size: 0.7rem;
            color: var(--grey-medium);
        }

        /* HTMX loading indicator */
        .htmx-indicator {
            display: none;
        }
        .htmx-request .htmx-indicator,
        .htmx-request.htmx-indicator {
            display: inline-block;
        }

        /* ============ RESPONSIVE ============ */
        @media (max-width: 768px) {
            html { font-size: 13px; }
            .content-wrapper { padding: 0.75rem; }
        }
        @media (min-width: 768px) and (max-width: 1200px) {
            html { font-size: 14px; }
        }
    </style>

    {% block extra_css %}{% endblock %}
</head>
<body>
    <!-- Sidebar Overlay (mobile) -->
    <div class="sidebar-overlay" onclick="document.body.classList.remove('sidebar-open')"></div>

    <!-- Sidebar Navigation -->
    <nav class="sidebar" id="sidebar">
        <a class="sidebar-brand" href="{% url 'stiftung:home' %}">
            <i class="fas fa-landmark"></i>
            <span>vHTV Stiftung</span>
        </a>

        <!-- Dashboard -->
        <div class="sidebar-section">
            <a class="sidebar-link {% if request.resolver_match.url_name == 'home' %}active{% endif %}" href="{% url 'stiftung:home' %}">
                <i class="fas fa-tachometer-alt"></i>
                <span>Dashboard</span>
            </a>
        </div>

        <!-- Personen -->
        <div class="sidebar-section">
            <div class="sidebar-heading">Personen</div>
            <a class="sidebar-link" href="{% url 'stiftung:destinataer_list' %}">
                <i class="fas fa-users"></i>
                <span>Destinataere</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:onboarding_einladung_liste' %}">
                <i class="fas fa-user-plus"></i>
                <span>Onboarding</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:foerderung_list' %}">
                <i class="fas fa-gift"></i>
                <span>Foerderungen</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:email_eingang_list' %}">
                <i class="fas fa-envelope-open-text"></i>
                <span>E-Mail Eingang</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:paechter_list' %}">
                <i class="fas fa-user-tie"></i>
                <span>Paechter</span>
            </a>
        </div>

        <!-- Land -->
        <div class="sidebar-section">
            <div class="sidebar-heading">Land & Pacht</div>
            <a class="sidebar-link" href="{% url 'stiftung:land_list' %}">
                <i class="fas fa-map"></i>
                <span>Laendereien</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:verpachtung_list' %}">
                <i class="fas fa-handshake"></i>
                <span>Verpachtungen</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:land_abrechnung_list' %}">
                <i class="fas fa-calculator"></i>
                <span>Abrechnungen</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:paechter_workflow' %}">
                <i class="fas fa-tractor"></i>
                <span>Pacht-Workflow</span>
            </a>
        </div>

        <!-- Finanzen -->
        <div class="sidebar-section">
            <div class="sidebar-heading">Finanzen</div>
            <a class="sidebar-link" href="{% url 'stiftung:unterstuetzungen_all' %}">
                <i class="fas fa-hand-holding-usd"></i>
                <span>Unterstuetzungen</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:zahlungs_pipeline' %}">
                <i class="fas fa-tasks"></i>
                <span>Zahlungs-Pipeline</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:nachweis_board' %}">
                <i class="fas fa-th"></i>
                <span>Nachweis-Board</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:geschaeftsfuehrung' %}">
                <i class="fas fa-briefcase"></i>
                <span>Geschaeftsfuehrung</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:bericht_list' %}">
                <i class="fas fa-chart-bar"></i>
                <span>Berichte</span>
            </a>
        </div>

        <!-- Dokumente -->
        <div class="sidebar-section">
            <div class="sidebar-heading">Dokumente</div>
            <a class="sidebar-link" href="{% url 'stiftung:dms_list' %}">
                <i class="fas fa-folder-open"></i>
                <span>Dokumente</span>
            </a>
        </div>

        <!-- Daten -->
        <div class="sidebar-section">
            <div class="sidebar-heading">Daten</div>
            <a class="sidebar-link" href="{% url 'stiftung:import_export_hub' %}">
                <i class="fas fa-exchange-alt"></i>
                <span>Import & Export</span>
            </a>
        </div>

        <!-- System -->
        <div class="sidebar-section">
            <div class="sidebar-heading">System</div>
            <a class="sidebar-link" href="{% url 'stiftung:kalender' %}">
                <i class="fas fa-calendar-alt"></i>
                <span>Kalender</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:veranstaltung_list' %}">
                <i class="fas fa-glass-cheers"></i>
                <span>Veranstaltungen</span>
            </a>
            <a class="sidebar-link" href="{% url 'stiftung:geschichte_list' %}">
                <i class="fas fa-book-open"></i>
                <span>Geschichte</span>
            </a>
            <a class="sidebar-link" href="https://ahnenforschung.vhtv-stiftung.de" target="_blank">
                <i class="fas fa-tree"></i>
                <span>Ahnenforschung</span>
            </a>
            {% if perms.stiftung.access_administration %}
            <a class="sidebar-link" href="{% url 'stiftung:administration' %}">
                <i class="fas fa-cogs"></i>
                <span>Administration</span>
            </a>
            {% endif %}
        </div>
    </nav>

    <!-- Top Bar -->
    <header class="topbar">
        <button class="topbar-toggle" onclick="toggleSidebar()" title="Sidebar umschalten">
            <i class="fas fa-bars"></i>
        </button>

        <div class="topbar-breadcrumb">
            {% block breadcrumb %}
            <a href="{% url 'stiftung:home' %}">Stiftungsverwaltung</a>
            {% endblock %}
        </div>

        <div class="topbar-actions">
            {% if user.is_authenticated %}
            <div class="dropdown">
                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    <i class="fas fa-user me-1"></i>{{ user.username }}
                    {% if user.is_superuser %}<span class="badge bg-danger ms-1">Admin</span>{% endif %}
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="{% url 'stiftung:user_detail' user.pk %}"><i class="fas fa-user me-2"></i>Mein Profil</a></li>
                    <li><a class="dropdown-item" href="{% url 'stiftung:two_factor_setup' %}"><i class="fas fa-shield-alt me-2"></i>2FA verwalten</a></li>
                    {% if perms.stiftung.manage_users %}
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" href="{% url 'stiftung:user_management' %}"><i class="fas fa-users-cog me-2"></i>Benutzerverwaltung</a></li>
                    {% endif %}
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" href="{% url 'stiftung:logout' %}"><i class="fas fa-sign-out-alt me-2"></i>Abmelden</a></li>
                </ul>
            </div>
            {% endif %}
        </div>
    </header>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Messages -->
        {% if messages %}
        <div class="content-wrapper" style="padding-bottom: 0;">
            {% for message in messages %}
            <div class="alert alert-{% if message.tags == 'error' %}danger{% else %}{{ message.tags }}{% endif %} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            {% endfor %}
        </div>
        {% endif %}

        <!-- Page Content -->
        <div class="content-wrapper">
            {% block content %}{% endblock %}
        </div>

        <!-- Footer -->
        <footer class="main-footer">
            &copy; 2026 van Hees-Theyssen-Vogel'sche Stiftung &middot;
            <small>Vision 2026 &middot; v{{ APP_VERSION }}</small>
        </footer>
    </main>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- HTMX -->
    <script src="https://unpkg.com/htmx.org@2.0.4" integrity="sha384-HGfztofotfshcF7+8n44JQL2oJmowVChPTg48S+jvZoztPfvwD79OC/LTtG6dMp+" crossorigin="anonymous"></script>
    <!-- Alpine.js -->
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.14.8/dist/cdn.min.js"></script>

    <script>
        // HTMX CSRF token setup
        document.body.addEventListener('htmx:configRequest', function(evt) {
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]')?.value
                || '{{ csrf_token }}';
            evt.detail.headers['X-CSRFToken'] = csrfToken;
        });

        // Sidebar toggle
        function toggleSidebar() {
            if (window.innerWidth < 992) {
                document.body.classList.toggle('sidebar-open');
            } else {
                document.body.classList.toggle('sidebar-collapsed');
                localStorage.setItem('sidebar-collapsed', document.body.classList.contains('sidebar-collapsed'));
            }
        }

        // Restore sidebar state
        if (localStorage.getItem('sidebar-collapsed') === 'true' && window.innerWidth >= 992) {
            document.body.classList.add('sidebar-collapsed');
        }
    </script>

    {% block javascript %}{% endblock %}

    <!-- Phase 4: Globale Suche (Cmd+K) -->
    <div id="global-search-overlay" style="display:none; position:fixed; inset:0; z-index:9999; background:rgba(0,0,0,0.5);" onclick="closeGlobalSearch()">
    </div>
    <div id="global-search-modal" style="display:none; position:fixed; top:15%; left:50%; transform:translateX(-50%); z-index:10000; width:min(600px, 90vw); background:#fff; border-radius:0.75rem; box-shadow:0 20px 60px rgba(0,0,0,0.3); overflow:hidden;">
        <div style="padding:0.75rem 1rem; border-bottom:1px solid #e9ecef; display:flex; align-items:center; gap:0.5rem;">
            <i class="fas fa-search" style="color:#6c757d;"></i>
            <input id="global-search-input" type="text" placeholder="Suche über alle Bereiche..." autocomplete="off"
                   style="flex:1; border:none; outline:none; font-size:1rem; background:transparent; color:#212529;">
            <kbd style="font-size:0.75rem; padding:2px 6px; background:#f8f9fa; border:1px solid #dee2e6; border-radius:4px; color:#6c757d;">Esc</kbd>
        </div>
        <div id="global-search-results" style="max-height:420px; overflow-y:auto; padding:0.5rem 0;">
            <div class="px-3 py-4 text-center text-muted" id="global-search-hint">
                <i class="fas fa-search fa-2x mb-2 d-block" style="opacity:0.3;"></i>
                Mindestens 2 Zeichen eingeben …
            </div>
        </div>
    </div>

    <!-- Suche-Trigger in Topbar -->
    <style>
        #global-search-btn {
            background: none;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 4px 10px;
            color: #6c757d;
            font-size: 0.85rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            white-space: nowrap;
            transition: border-color 0.15s, color 0.15s;
        }
        #global-search-btn:hover {
            border-color: var(--racing-green);
            color: var(--racing-green);
        }
        .search-result-item {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.6rem 1rem;
            cursor: pointer;
            text-decoration: none;
            color: #212529;
            transition: background 0.1s;
        }
        .search-result-item:hover, .search-result-item.highlighted {
            background: #f0f7f4;
            color: var(--racing-green-dark);
        }
        .search-result-icon {
            width: 32px; height: 32px;
            border-radius: 50%;
            background: var(--racing-green);
            color: white;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0;
            font-size: 0.8rem;
        }
        .search-result-typ {
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: #6c757d;
        }
        .search-group-label {
            padding: 0.25rem 1rem;
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: #adb5bd;
            font-weight: 600;
            border-top: 1px solid #f0f0f0;
            margin-top: 0.25rem;
        }
        .search-group-label:first-child { border-top: none; margin-top: 0; }
    </style>

    <script>
    (function() {
        const overlay = document.getElementById('global-search-overlay');
        const modal = document.getElementById('global-search-modal');
        const input = document.getElementById('global-search-input');
        const resultsEl = document.getElementById('global-search-results');
        const hintEl = document.getElementById('global-search-hint');
        let debounceTimer = null;
        let currentHighlight = -1;
        let resultLinks = [];

        function openGlobalSearch() {
            overlay.style.display = 'block';
            modal.style.display = 'block';
            input.focus();
            input.select();
        }

        window.closeGlobalSearch = function() {
            overlay.style.display = 'none';
            modal.style.display = 'none';
        };

        // Cmd+K / Ctrl+K öffnet Suche
        document.addEventListener('keydown', function(e) {
            if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
                e.preventDefault();
                if (modal.style.display === 'block') {
                    closeGlobalSearch();
                } else {
                    openGlobalSearch();
                }
            }
            if (e.key === 'Escape' && modal.style.display === 'block') {
                closeGlobalSearch();
            }
            // Keyboard navigation
            if (modal.style.display === 'block' && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
                e.preventDefault();
                resultLinks = Array.from(resultsEl.querySelectorAll('.search-result-item'));
                if (!resultLinks.length) return;
                resultLinks.forEach(l => l.classList.remove('highlighted'));
                if (e.key === 'ArrowDown') currentHighlight = Math.min(currentHighlight + 1, resultLinks.length - 1);
                else currentHighlight = Math.max(currentHighlight - 1, 0);
                if (currentHighlight >= 0) {
                    resultLinks[currentHighlight].classList.add('highlighted');
                    resultLinks[currentHighlight].scrollIntoView({ block: 'nearest' });
                }
            }
            if (modal.style.display === 'block' && e.key === 'Enter') {
                resultLinks = Array.from(resultsEl.querySelectorAll('.search-result-item'));
                if (currentHighlight >= 0 && resultLinks[currentHighlight]) {
                    window.location.href = resultLinks[currentHighlight].href;
                } else if (resultLinks.length === 1) {
                    window.location.href = resultLinks[0].href;
                }
            }
        });

        // Prevent modal click from closing
        modal.addEventListener('click', function(e) { e.stopPropagation(); });

        input.addEventListener('input', function() {
            clearTimeout(debounceTimer);
            currentHighlight = -1;
            const q = input.value.trim();
            if (q.length < 2) {
                hintEl.style.display = '';
                resultsEl.innerHTML = '';
                resultsEl.appendChild(hintEl);
                return;
            }
            debounceTimer = setTimeout(function() { doSearch(q); }, 200);
        });

        function doSearch(q) {
            fetch("{% url 'stiftung:globale_suche_api' %}?q=" + encodeURIComponent(q), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(r => r.json())
            .then(data => renderResults(data.results, q))
            .catch(() => {});
        }

        function renderResults(results, q) {
            resultsEl.innerHTML = '';
            if (!results || !results.length) {
                const empty = document.createElement('div');
                empty.className = 'px-3 py-4 text-center text-muted';
                empty.innerHTML = '<i class="fas fa-search-minus fa-2x mb-2 d-block" style="opacity:0.3;"></i>Keine Ergebnisse für „' + escapeHtml(q) + '"';
                resultsEl.appendChild(empty);
                return;
            }
            // Group by type
            const grouped = {};
            results.forEach(r => {
                if (!grouped[r.typ]) grouped[r.typ] = [];
                grouped[r.typ].push(r);
            });
            Object.entries(grouped).forEach(([typ, items]) => {
                const label = document.createElement('div');
                label.className = 'search-group-label';
                label.textContent = typ;
                resultsEl.appendChild(label);
                items.forEach(item => {
                    const a = document.createElement('a');
                    a.className = 'search-result-item';
                    a.href = item.url;
                    a.innerHTML = `
                        <div class="search-result-icon"><i class="${item.icon}"></i></div>
                        <div style="min-width:0;">
                            <div style="font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${escapeHtml(item.titel)}</div>
                            ${item.untertitel ? '<div class="search-result-typ">' + escapeHtml(item.untertitel) + '</div>' : ''}
                        </div>`;
                    a.addEventListener('click', closeGlobalSearch);
                    resultsEl.appendChild(a);
                });
            });
        }

        function escapeHtml(s) {
            return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
        }

        // Inject search button into topbar
        document.addEventListener('DOMContentLoaded', function() {
            const topbarActions = document.querySelector('.topbar-actions');
            if (topbarActions) {
                const btn = document.createElement('button');
                btn.id = 'global-search-btn';
                btn.onclick = openGlobalSearch;
                btn.innerHTML = '<i class="fas fa-search"></i> Suche <kbd style="font-size:0.7rem; padding:1px 4px; background:#f8f9fa; border:1px solid #dee2e6; border-radius:3px; margin-left:4px;">⌘K</kbd>';
                topbarActions.insertBefore(btn, topbarActions.firstChild);
            }
        });
    })();
    </script>

    {% if user.is_authenticated and perms.stiftung.can_use_agent %}
    <!-- ══════════════════════════════════════════════════════════════
         AI Agent Chat-Widget
         ══════════════════════════════════════════════════════════════ -->
    <style>
        #agent-fab {
            position: fixed;
            bottom: 1.5rem;
            right: 1.5rem;
            z-index: 9000;
            width: 52px;
            height: 52px;
            border-radius: 50%;
            background: var(--racing-green);
            color: #fff;
            border: none;
            box-shadow: 0 4px 16px rgba(0,0,0,0.25);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            transition: background 0.2s, transform 0.15s;
        }
        #agent-fab:hover { background: var(--racing-green-light); transform: scale(1.07); }

        #agent-panel {
            position: fixed;
            bottom: 5.5rem;
            right: 1.5rem;
            z-index: 9001;
            width: min(420px, calc(100vw - 2rem));
            max-height: calc(100vh - 7rem);
            background: #fff;
            border-radius: 1rem;
            box-shadow: 0 8px 40px rgba(0,0,0,0.2);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            transform: translateY(10px) scale(0.97);
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.2s, transform 0.2s;
        }
        #agent-panel.open {
            opacity: 1;
            transform: translateY(0) scale(1);
            pointer-events: all;
        }

        #agent-header {
            background: var(--racing-green);
            color: #fff;
            padding: 0.75rem 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            flex-shrink: 0;
        }
        #agent-header h6 { margin: 0; font-size: 0.9rem; font-weight: 600; flex: 1; }
        #agent-header button { background: none; border: none; color: rgba(255,255,255,0.7); cursor: pointer; padding: 0 4px; font-size: 1rem; }
        #agent-header button:hover { color: #fff; }

        #agent-session-bar {
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 0.4rem 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            flex-shrink: 0;
        }
        #agent-session-bar select {
            flex: 1;
            font-size: 0.8rem;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 2px 6px;
            background: #fff;
        }
        #agent-session-bar button { font-size: 0.75rem; white-space: nowrap; }

        #agent-messages {
            flex: 1;
            overflow-y: auto;
            padding: 0.75rem;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            min-height: 200px;
        }

        .agent-msg {
            max-width: 85%;
            padding: 0.5rem 0.75rem;
            border-radius: 0.75rem;
            font-size: 0.85rem;
            line-height: 1.5;
            word-break: break-word;
        }
        .agent-msg.user {
            background: var(--racing-green);
            color: #fff;
            align-self: flex-end;
            border-bottom-right-radius: 4px;
        }
        .agent-msg.assistant {
            background: #f0f2f5;
            color: #212529;
            align-self: flex-start;
            border-bottom-left-radius: 4px;
        }
        .agent-msg.tool-indicator {
            background: #fff3cd;
            color: #856404;
            align-self: flex-start;
            font-size: 0.78rem;
            padding: 0.3rem 0.6rem;
        }
        .agent-msg pre { margin: 0; white-space: pre-wrap; font-family: inherit; }
        .agent-msg code { background: rgba(0,0,0,0.08); border-radius: 3px; padding: 1px 4px; font-size: 0.82em; }

        #agent-input-area {
            border-top: 1px solid #e9ecef;
            padding: 0.6rem 0.75rem;
            display: flex;
            gap: 0.5rem;
            flex-shrink: 0;
        }
        #agent-input {
            flex: 1;
            border: 1px solid #dee2e6;
            border-radius: 0.5rem;
            padding: 0.4rem 0.65rem;
            font-size: 0.85rem;
            resize: none;
            min-height: 36px;
            max-height: 120px;
            outline: none;
            font-family: inherit;
        }
        #agent-input:focus { border-color: var(--racing-green); }
        #agent-send-btn {
            background: var(--racing-green);
            color: #fff;
            border: none;
            border-radius: 0.5rem;
            padding: 0 0.75rem;
            cursor: pointer;
            font-size: 1rem;
            transition: background 0.15s;
            align-self: flex-end;
            height: 36px;
        }
        #agent-send-btn:disabled { background: #adb5bd; cursor: not-allowed; }
        #agent-send-btn:not(:disabled):hover { background: var(--racing-green-light); }

        .agent-typing { display: flex; gap: 4px; align-items: center; padding: 0.5rem 0.75rem; }
        .agent-typing span {
            width: 7px; height: 7px; background: #adb5bd;
            border-radius: 50%; animation: agent-bounce 1s infinite;
        }
        .agent-typing span:nth-child(2) { animation-delay: 0.15s; }
        .agent-typing span:nth-child(3) { animation-delay: 0.3s; }
        @keyframes agent-bounce {
            0%,80%,100% { transform: translateY(0); }
            40% { transform: translateY(-6px); }
        }
    </style>

    <!-- FAB Button -->
    <button id="agent-fab" title="AI-Assistent öffnen" onclick="agentToggle()">
        <i class="fas fa-robot"></i>
    </button>

    <!-- Chat Panel -->
    <div id="agent-panel">
        <div id="agent-header">
            <i class="fas fa-robot"></i>
            <h6>RentmeisterAI</h6>
            <button onclick="agentNewSession()" title="Neue Unterhaltung"><i class="fas fa-plus"></i></button>
            <button onclick="agentToggle()" title="Schließen"><i class="fas fa-times"></i></button>
        </div>
        <div id="agent-session-bar">
            <select id="agent-session-select" onchange="agentLoadSession(this.value)" title="Sitzung wechseln">
                <option value="">— Neue Unterhaltung —</option>
            </select>
            <button class="btn btn-sm btn-outline-danger" onclick="agentDeleteSession()" title="Sitzung löschen">
                <i class="fas fa-trash-alt"></i>
            </button>
        </div>
        <div id="agent-messages">
            <div class="agent-msg assistant">
                Guten Tag! Ich bin RentmeisterAI. Wie kann ich Ihnen helfen?
            </div>
        </div>
        <div id="agent-input-area">
            <textarea id="agent-input" placeholder="Nachricht eingeben… (Enter = senden)" rows="1"
                onkeydown="agentKeydown(event)"></textarea>
            <button id="agent-send-btn" onclick="agentSend()" title="Senden">
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    </div>

    <script>
    (function() {
        const CSRF = '{{ csrf_token }}';
        let currentSessionId = null;
        let isStreaming = false;

        window.agentToggle = function() {
            const panel = document.getElementById('agent-panel');
            const isOpen = panel.classList.contains('open');
            panel.classList.toggle('open');
            if (!isOpen) {
                agentLoadSessions();
                document.getElementById('agent-input').focus();
            }
        };

        window.agentNewSession = function() {
            currentSessionId = null;
            document.getElementById('agent-session-select').value = '';
            document.getElementById('agent-messages').innerHTML =
                '<div class="agent-msg assistant">Neue Unterhaltung gestartet. Wie kann ich helfen?</div>';
        };

        window.agentKeydown = function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                agentSend();
            }
        };

        window.agentSend = async function() {
            if (isStreaming) return;
            const input = document.getElementById('agent-input');
            const msg = input.value.trim();
            if (!msg) return;

            input.value = '';
            autoResizeTextarea(input);

            appendMessage('user', msg);
            const typingEl = appendTyping();
            setSending(true);

            // Seitenkontext: URL + Titel
            const pageContext = `Seite: ${document.title}\nURL: ${window.location.href}`;

            try {
                const res = await fetch('/agent/chat/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': CSRF,
                    },
                    body: JSON.stringify({
                        message: msg,
                        session_id: currentSessionId,
                        page_context: pageContext,
                    }),
                });

                if (!res.ok) {
                    const err = await res.json().catch(() => ({}));
                    throw new Error(err.error || `HTTP ${res.status}`);
                }

                const data = await res.json();
                currentSessionId = data.session_id;

                // Session-Select aktualisieren
                updateSessionSelect(data.session_id);

                // SSE-Stream starten
                typingEl.remove();
                await agentStream(data.stream_url);

            } catch (e) {
                typingEl.remove();
                appendMessage('assistant', `Fehler: ${e.message}`);
            } finally {
                setSending(false);
            }
        };

        async function agentStream(url) {
            const msgEl = appendMessage('assistant', '');
            const contentEl = msgEl.querySelector('.agent-text');

            return new Promise((resolve) => {
                const es = new EventSource(url);
                es.onmessage = function(e) {
                    try {
                        const chunk = JSON.parse(e.data);
                        if (chunk.type === 'text') {
                            contentEl.textContent += chunk.content;
                            scrollMessages();
                        } else if (chunk.type === 'tool_start') {
                            appendToolIndicator(chunk.name);
                        } else if (chunk.type === 'done') {
                            es.close();
                            renderMarkdown(contentEl);
                            agentLoadSessions();
                            resolve();
                        } else if (chunk.type === 'error') {
                            contentEl.textContent = `Fehler: ${chunk.message}`;
                            es.close();
                            resolve();
                        }
                    } catch(err) { /* ignore parse errors */ }
                };
                es.onerror = function() {
                    es.close();
                    if (!contentEl.textContent) {
                        contentEl.textContent = 'Verbindungsfehler.';
                    }
                    resolve();
                };
            });
        }

        function appendMessage(role, text) {
            const messages = document.getElementById('agent-messages');
            const div = document.createElement('div');
            div.className = `agent-msg ${role}`;
            const span = document.createElement('span');
            span.className = 'agent-text';
            span.textContent = text;
            div.appendChild(span);
            messages.appendChild(div);
            scrollMessages();
            return div;
        }

        function appendTyping() {
            const messages = document.getElementById('agent-messages');
            const div = document.createElement('div');
            div.className = 'agent-msg assistant agent-typing-wrap';
            div.innerHTML = '<div class="agent-typing"><span></span><span></span><span></span></div>';
            messages.appendChild(div);
            scrollMessages();
            return div;
        }

        function appendToolIndicator(toolName) {
            const messages = document.getElementById('agent-messages');
            const div = document.createElement('div');
            div.className = 'agent-msg tool-indicator';
            div.innerHTML = `<i class="fas fa-cog fa-spin me-1"></i> Werkzeug: <em>${escHtml(toolName)}</em>`;
            messages.appendChild(div);
            scrollMessages();
        }

        function renderMarkdown(el) {
            // Simple markdown: **bold**, `code`, newlines
            let html = escHtml(el.textContent)
                .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
                .replace(/`([^`]+)`/g, '<code>$1</code>')
                .replace(/\n/g, '<br>');
            el.innerHTML = html;
        }

        function scrollMessages() {
            const m = document.getElementById('agent-messages');
            m.scrollTop = m.scrollHeight;
        }

        function setSending(v) {
            isStreaming = v;
            document.getElementById('agent-send-btn').disabled = v;
            document.getElementById('agent-input').disabled = v;
        }

        function autoResizeTextarea(el) {
            el.style.height = 'auto';
            el.style.height = Math.min(el.scrollHeight, 120) + 'px';
        }

        document.addEventListener('DOMContentLoaded', function() {
            const input = document.getElementById('agent-input');
            if (input) input.addEventListener('input', () => autoResizeTextarea(input));
        });

        window.agentLoadSessions = async function() {
            try {
                const res = await fetch('/agent/sessions/');
                if (!res.ok) return;
                const data = await res.json();
                const sel = document.getElementById('agent-session-select');
                // Keep current value
                const current = sel.value;
                sel.innerHTML = '<option value="">— Neue Unterhaltung —</option>';
                data.sessions.forEach(s => {
                    const opt = document.createElement('option');
                    opt.value = s.id;
                    opt.textContent = (s.title || 'Unterhaltung').substring(0, 40);
                    sel.appendChild(opt);
                });
                if (currentSessionId) sel.value = currentSessionId;
                else if (current) sel.value = current;
            } catch(e) { /* ignore */ }
        };

        window.agentLoadSession = async function(sessionId) {
            if (!sessionId) { agentNewSession(); return; }
            currentSessionId = sessionId;
            try {
                const res = await fetch(`/agent/sessions/${sessionId}/`);
                if (!res.ok) return;
                const data = await res.json();
                const messages = document.getElementById('agent-messages');
                messages.innerHTML = '';
                data.messages.forEach(m => {
                    if (m.role === 'tool') return;
                    const div = appendMessage(m.role, m.content);
                    renderMarkdown(div.querySelector('.agent-text'));
                });
                if (data.messages.length === 0) {
                    appendMessage('assistant', 'Wie kann ich Ihnen helfen?');
                }
            } catch(e) { /* ignore */ }
        };

        window.agentDeleteSession = async function() {
            if (!currentSessionId) return;
            if (!confirm('Diese Unterhaltung wirklich löschen?')) return;
            try {
                await fetch(`/agent/sessions/${currentSessionId}/loeschen/`, {
                    method: 'POST',
                    headers: { 'X-CSRFToken': CSRF },
                });
                agentNewSession();
                agentLoadSessions();
            } catch(e) { /* ignore */ }
        };

        function updateSessionSelect(id) {
            const sel = document.getElementById('agent-session-select');
            let found = false;
            for (const opt of sel.options) { if (opt.value === id) { found = true; break; } }
            if (!found) {
                const opt = document.createElement('option');
                opt.value = id;
                opt.textContent = '(aktuelle Unterhaltung)';
                sel.appendChild(opt);
            }
            sel.value = id;
        }

        function escHtml(s) {
            return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
        }
    })();
    </script>
    {% endif %}
</body>
</html>