<?php
/** @var array<string, mixed> $pageData */
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <?php $themeCss = app_tenant_theme_root_css($tenantSettings ?? app_tenant_settings_defaults()); ?>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Die Kaffeeliste</title>
    <style>
        :root{
            <?= $themeCss ?>
            --line:rgba(143,158,191,.16);
            --line-strong:rgba(174,189,223,.26);
            --shadow:0 24px 64px rgba(1,6,18,.30);
            --radius:18px;
            --surface-0:#0f1720;
            --surface-1:rgba(18,26,36,.84);
            --surface-2:rgba(23,32,45,.92);
            --surface-3:rgba(29,40,55,.96);
            --text-strong:#f4f7ff;
            --text-soft:rgba(219,228,248,.74);
        }
        *{box-sizing:border-box}
        body{
            margin:0;
            min-height:100vh;
            color:var(--text-strong);
            font-family:"Aptos","Segoe UI",sans-serif;
            background:
                radial-gradient(circle at top center, rgba(88,122,255,.18), transparent 26%),
                radial-gradient(circle at 18% 12%, rgba(var(--brand-rgb),.16), transparent 22%),
                linear-gradient(180deg,var(--surface-0) 0%,color-mix(in srgb,var(--surface-0) 82%, black 18%) 100%);
        }
        a{color:inherit;text-decoration:none}
        .button,button{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            padding:10px 14px;
            border-radius:10px;
            border:1px solid transparent;
            background:var(--brand);
            color:#fff;
            font:inherit;
            font-weight:700;
            cursor:pointer;
        }
        .button--ghost{
            background:transparent;
            color:var(--text-strong);
            border-color:var(--line-strong);
        }
        .page-shell{
            width:100%;
            margin:0 0 34px;
            display:grid;
            gap:16px;
        }
        .site-header{
            position:sticky;
            top:0;
            z-index:30;
            width:100vw;
            margin-left:calc(50% - 50vw);
        }
        .site-header__inner{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:18px;
            width:100%;
            margin:0;
            min-height:72px;
            padding:12px 24px;
            border:0;
            border-bottom:1px solid var(--line);
            border-radius:0;
            background:color-mix(in srgb,var(--surface-1) 88%, rgba(var(--brand-rgb),.12) 12%);
            box-shadow:var(--shadow);
            backdrop-filter:blur(18px);
        }
        .site-brand{display:flex;align-items:center;gap:12px;min-width:0}
        .site-brand__mark{
            width:36px;
            height:36px;
            border-radius:10px;
            display:grid;
            place-items:center;
            background:linear-gradient(135deg,#587aff 0%,#243a91 100%);
            color:#fff;
            font-weight:800;
            box-shadow:none;
        }
        .site-brand__title{margin:0;font-family:"Inter Tight","Aptos","Segoe UI",sans-serif;font-size:1.08rem;letter-spacing:-.04em;color:var(--text-strong)}
        .site-brand__subtitle{margin:2px 0 0;color:var(--text-soft);font-size:.9rem}
        .site-nav,.site-actions,.actions,.context{display:flex;flex-wrap:wrap;gap:10px;align-items:center}
        .site-nav__link{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            min-height:34px;
            padding:0 .3rem;
            border-radius:6px;
            border:1px solid transparent;
            color:var(--text-soft);
            font-weight:600;
            font-size:.96rem;
        }
        .site-nav__link:hover{text-decoration:none;color:var(--text-strong);background:rgba(var(--brand-rgb),.09);border-color:rgba(var(--brand-rgb),.18)}
        .site-nav__link.active{background:rgba(var(--brand-rgb),.16);color:var(--text-strong);border-color:rgba(var(--brand-rgb),.28)}
        .site-more{position:relative}
        .site-more[open]{z-index:25}
        .site-more__toggle{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 .6rem;border-radius:8px;border:1px solid var(--line);background:rgba(255,255,255,.03);color:var(--text-soft);font-size:.96rem;font-weight:600;cursor:pointer;list-style:none}
        .site-more__toggle::-webkit-details-marker{display:none}
        .site-more__panel{position:absolute;right:0;top:calc(100% + 10px);min-width:240px;padding:12px;border-radius:14px;border:1px solid var(--line);background:var(--surface-3);box-shadow:var(--shadow);display:grid;gap:8px}
        .site-more__label{font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--text-soft)}
        .hero,.card,.alert{
            border:1px solid var(--line);
            border-radius:16px;
            background:var(--surface-2);
            box-shadow:var(--shadow);
        }
        .hero__title,.card h2,.card h3{
            font-family:"Inter Tight","Aptos","Segoe UI",sans-serif;
            letter-spacing:-.04em;
            color:var(--text-strong);
        }
        .muted,p{color:var(--text-soft)}
        .site-mobile{display:none}
        .site-mobile__toggle{
            display:none;
            align-items:center;
            justify-content:center;
            gap:10px;
            cursor:pointer;
            min-height:38px;
            padding:.45rem .72rem;
            border-radius:10px;
            border:1px solid var(--line-strong);
            background:rgba(255,255,255,.04);
            color:var(--text-strong);
            font-weight:700;
        }
        .site-mobile__toggle::before{
            content:"";
            display:block;
            width:18px;
            height:2px;
            border-radius:999px;
            background:currentColor;
            box-shadow:0 -6px 0 currentColor,0 6px 0 currentColor;
        }
        .mobile-drawer{position:fixed;inset:0;display:none;z-index:55}
        .mobile-drawer.is-open{display:block}
        .mobile-drawer__scrim{position:absolute;inset:0;background:rgba(4,10,18,.58);backdrop-filter:blur(6px)}
        .mobile-drawer__panel{
            position:absolute;
            right:0;
            top:0;
            bottom:0;
            width:min(100vw,420px);
            max-width:100%;
            padding:18px 16px calc(28px + env(safe-area-inset-bottom));
            background:var(--surface-3);
            border-left:1px solid var(--line);
            box-shadow:var(--shadow);
            display:grid;
            grid-template-rows:auto 1fr auto;
            gap:18px;
            overflow:auto;
        }
        .mobile-drawer__header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}
        .mobile-drawer__title{margin:0;font-size:1.08rem;color:var(--text-strong)}
        .mobile-drawer__subtitle{margin:4px 0 0;color:var(--text-soft);font-size:.9rem}
        .mobile-drawer__close{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            width:40px;
            height:40px;
            border-radius:999px;
            border:1px solid var(--line);
            background:rgba(255,255,255,.04);
            color:var(--text-strong);
            font-size:1.15rem;
            font-weight:700;
            cursor:pointer;
        }
        .mobile-drawer__section{display:grid;gap:10px}
        .mobile-drawer__label{font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--text-soft)}
        .mobile-drawer__links{display:grid;gap:8px}
        .mobile-drawer__link{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:12px;
            padding:.9rem 1rem;
            border-radius:14px;
            border:1px solid var(--line);
            background:rgba(255,255,255,.04);
            color:var(--text-strong);
            font-weight:700;
        }
        .mobile-drawer__link.active{background:rgba(88,122,255,.16);border-color:rgba(88,122,255,.28)}
        .mobile-drawer__footer{display:grid;gap:12px;padding-top:8px;border-top:1px solid var(--line)}
        .mobile-drawer__meta{display:grid;gap:4px}
        .mobile-bottom-nav{display:none}
        .mobile-bottom-nav__link,.mobile-bottom-nav__toggle{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:6px;
            min-height:56px;
            padding:0 8px;
            border:0;
            background:transparent;
            color:var(--text-soft);
            font:inherit;
            font-weight:700;
        }
        .mobile-bottom-nav__link.active,.mobile-bottom-nav__toggle.active{color:var(--text-strong)}
        .mobile-bottom-nav__icon{font-size:1rem;line-height:1}
        .mobile-bottom-nav__label{font-size:.74rem}
        .content{width:min(1260px,calc(100% - 28px));margin:0 auto;min-width:0;display:grid;gap:18px}
        .hero{
            padding:24px;
            display:grid;
            gap:18px;
            background:linear-gradient(180deg,rgba(18,25,42,.96),rgba(13,19,33,.92));
        }
        .hero__kicker{
            margin:0 0 10px;
            color:#8aa0d0;
            text-transform:uppercase;
            letter-spacing:.16em;
            font-size:.8rem;
            font-weight:800;
        }
        .hero__title{
            margin:0;
            font-size:clamp(1.9rem,4vw,3rem);
            line-height:1.05;
        }
        .hero__lead{margin:0;max-width:72ch;font-size:1.02rem;line-height:1.65}
        .grid{display:grid;gap:18px}
        .grid--2{grid-template-columns:repeat(2,minmax(0,1fr))}
        .grid--3{grid-template-columns:repeat(3,minmax(0,1fr))}
        .grid--4{grid-template-columns:repeat(4,minmax(0,1fr))}
        .card{padding:22px}
        .card h2,.card h3{margin:0 0 12px}
        .eyebrow{
            display:inline-block;
            margin-bottom:10px;
            color:var(--accent);
            font-size:.82rem;
            font-weight:800;
            letter-spacing:.12em;
            text-transform:uppercase;
        }
        .metric{
            padding:18px;
            border-radius:16px;
            border:1px solid var(--line);
            background:rgba(255,255,255,.04);
            display:grid;
            gap:8px;
        }
        .metric strong{font-size:1.8rem}
        .badge{
            display:inline-flex;
            align-items:center;
            padding:7px 12px;
            border-radius:999px;
            font-size:.86rem;
            font-weight:700;
            border:1px solid rgba(201,214,255,.12);
            background:rgba(255,255,255,.04);
            color:#dfe8ff;
        }
        .badge--neutral{background:rgba(88,122,255,.14);color:#dfe8ff}
        .badge--success{background:rgba(88,122,255,.14);color:#dfe8ff}
        .badge--warning{background:rgba(180,83,9,.18);color:#f5c68a}
        .badge--danger{background:rgba(185,28,28,.18);color:#f2a2a2}
        .alert{padding:16px 18px}
        .alert-success{background:rgba(88,122,255,.12)}
        .alert-warning{background:rgba(180,83,9,.16)}
        .alert-error{background:rgba(185,28,28,.16)}
        .alert-info{background:rgba(88,122,255,.1)}
        .split{display:grid;grid-template-columns:minmax(0,1.05fr) minmax(360px,.95fr);gap:18px}
        .stack{display:grid;gap:12px}
        .table{overflow-x:auto}
        table{width:100%;border-collapse:collapse;min-width:860px}
        th,td{padding:13px 10px;border-bottom:1px solid rgba(163,183,255,.1);text-align:left;vertical-align:top}
        th{font-size:.85rem;letter-spacing:.08em;text-transform:uppercase;color:rgba(193,205,232,.7)}
        label{display:flex;flex-direction:column;gap:8px;font-weight:700}
        input,select,textarea{width:100%;padding:12px 14px;border-radius:14px;border:1px solid var(--line);font:inherit;background:rgba(9,13,24,.82);color:var(--text-strong)}
        select{color-scheme:dark;background-color:rgba(9,13,24,.94)}
        select option,select optgroup{background:rgba(9,13,24,.98);color:#f4f7ff}
        textarea{min-height:120px}
        .timeline{display:grid;gap:12px}
        .timeline__item{padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.04);border:1px solid var(--line)}
        .timeline__meta{margin:0;color:var(--text-soft);font-size:.94rem;line-height:1.6}
        .timeline__title{margin:0 0 6px;font-weight:800}
        .pill{
            display:inline-flex;
            align-items:center;
            padding:7px 12px;
            border-radius:999px;
            border:1px solid rgba(201,214,255,.12);
            background:rgba(255,255,255,.04);
            color:#dfe8ff;
            font-size:.84rem;
            font-weight:700;
        }
        .status-grid{display:grid;gap:8px}
        .status{display:inline-flex;align-items:center;gap:8px}
        .status::before{content:"";width:8px;height:8px;border-radius:999px;background:var(--brand)}
        .status.is-new::before{background:var(--accent)}
        .status.is-waiting::before{background:#9a1f1f}
        .status.is-closed::before{background:#11623d}
        .mono{font-family:Consolas,monospace}
        .footer{margin-top:18px;text-align:center;color:rgba(209,217,235,.68);font-size:.92rem}
        @media(max-width:1180px){
            body.mobile-drawer-open{overflow:hidden}
            .content{width:min(100vw - 20px,1260px)}
            .page-shell{padding-bottom:94px}
            .site-header__inner{align-items:center;padding:12px 16px;min-height:68px;width:100%}
            .site-nav{display:none}
            .site-actions{gap:8px}
            .site-actions .badge,.site-actions .site-more{display:none}
            .site-mobile__toggle{display:inline-flex}
            .site-mobile{display:block}
            .split,.grid--2,.grid--3,.grid--4{grid-template-columns:1fr}
            table{min-width:0}
            .mobile-bottom-nav{
                position:fixed;
                left:10px;
                right:10px;
                bottom:max(10px,env(safe-area-inset-bottom));
                z-index:45;
                display:grid;
                grid-template-columns:repeat(4,minmax(0,1fr));
                gap:4px;
                padding:6px;
                border:1px solid var(--line);
                border-radius:18px;
                background:var(--surface-3);
                box-shadow:var(--shadow);
            }
        }
        @media(min-width:1181px){
            .site-mobile{display:none}
        }
    </style>
</head>
<body>
<main class="page-shell">
    <header class="site-header">
        <div class="site-header__inner">
            <a href="/dashboard/" class="site-brand">
                <div class="site-brand__mark">K</div>
                <div>
                    <h1 class="site-brand__title">Die Kaffeeliste</h1>
                    <p class="site-brand__subtitle">Support</p>
                </div>
            </a>

            <nav class="site-nav" aria-label="Tenant-Menü">
                <?php foreach ($tenantHeaderNavItems as $item): ?>
                    <a href="<?= support_h((string) ($item['href'] ?? '/')) ?>" class="site-nav__link <?= (($item['key'] ?? '') === 'support') ? 'active' : '' ?>" <?= (($item['key'] ?? '') === 'support') ? 'aria-current="page"' : '' ?>><?= support_h((string) ($item['label'] ?? 'Link')) ?></a>
                <?php endforeach; ?>
                <?php foreach ($tenantNavGroups as $group): ?>
                    <details class="site-more">
                        <summary class="site-more__toggle"><?= support_h((string) ($group['label'] ?? 'Mehr')) ?></summary>
                        <div class="site-more__panel">
                            <div class="site-more__label"><?= support_h((string) ($group['label'] ?? 'Mehr')) ?></div>
                            <?php foreach (($group['items'] ?? []) as $item): ?>
                                <a href="<?= support_h((string) ($item['href'] ?? '/')) ?>" class="site-nav__link <?= (($item['key'] ?? '') === 'support') ? 'active' : '' ?>" <?= (($item['key'] ?? '') === 'support') ? 'aria-current="page"' : '' ?>><?= support_h((string) ($item['label'] ?? 'Link')) ?></a>
                            <?php endforeach; ?>
                        </div>
                    </details>
                <?php endforeach; ?>
            </nav>

            <div class="site-actions">
                <?= support_badge($isManager ? 'Verantwortlichen-Sicht' : 'Mitgliedersicht', 'success') ?>
                <details class="site-more">
                    <summary class="site-more__toggle">Konto</summary>
                    <div class="site-more__panel">
                        <div class="site-more__label">Konto</div>
                        <a href="/profile/" class="site-nav__link">Persönliche Einstellungen</a>
                        <form method="post" action="/logout/"><button type="submit" class="button button--ghost" style="width:100%">Abmelden</button></form>
                    </div>
                </details>
                <button type="button" class="site-mobile__toggle" data-mobile-drawer-open>Menü</button>
            </div>
        </div>
    </header>

    <?php if ($mobileBottomNavItems !== []): ?>
        <div class="mobile-drawer" data-mobile-drawer>
            <button type="button" class="mobile-drawer__scrim" aria-label="Menü schließen" data-mobile-drawer-close></button>
            <aside class="mobile-drawer__panel" aria-label="Menü">
                <div class="mobile-drawer__header">
                    <div>
                        <h2 class="mobile-drawer__title">Menü</h2>
                        <p class="mobile-drawer__subtitle"><?= support_h((string) ($auth['tenant_name'] ?? 'Bereich')) ?></p>
                    </div>
                    <button type="button" class="mobile-drawer__close" aria-label="Schließen" data-mobile-drawer-close>&times;</button>
                </div>
                <?php if ($tenantHeaderNavItems !== []): ?>
                    <div class="mobile-drawer__section">
                        <div class="mobile-drawer__label">Kernnavigation</div>
                        <div class="mobile-drawer__links">
                            <?php foreach ($tenantHeaderNavItems as $item): ?>
                                <a href="<?= support_h((string) ($item['href'] ?? '/')) ?>" class="mobile-drawer__link <?= (($item['key'] ?? '') === 'support') ? 'active' : '' ?>" <?= (($item['key'] ?? '') === 'support') ? 'aria-current="page"' : '' ?>><?= support_h((string) ($item['label'] ?? 'Link')) ?></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
                <?php foreach ($tenantNavGroups as $group): ?>
                    <div class="mobile-drawer__section">
                        <div class="mobile-drawer__label"><?= support_h((string) ($group['label'] ?? 'Mehr')) ?></div>
                        <div class="mobile-drawer__links">
                            <?php foreach (($group['items'] ?? []) as $item): ?>
                                <a href="<?= support_h((string) ($item['href'] ?? '/')) ?>" class="mobile-drawer__link <?= (($item['key'] ?? '') === 'support') ? 'active' : '' ?>" <?= (($item['key'] ?? '') === 'support') ? 'aria-current="page"' : '' ?>><?= support_h((string) ($item['label'] ?? 'Link')) ?></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
                <div class="mobile-drawer__footer">
                    <div class="mobile-drawer__section">
                        <div class="mobile-drawer__label">Konto</div>
                        <div class="mobile-drawer__links">
                            <a href="/profile/" class="mobile-drawer__link">Persönliche Einstellungen</a>
                        </div>
                    </div>
                    <form method="post" action="/logout/"><button type="submit" class="button button--ghost" style="width:100%">Abmelden</button></form>
                </div>
            </aside>
        </div>
    <?php endif; ?>

    <div class="content">
        <section class="hero">
            <div>
                <p class="hero__kicker">Support</p>
                <h2 class="hero__title">Support</h2>
                <p class="hero__lead">
                    Mitglieder legen hier Vorgänge an. Verantwortliche verfolgen, beantworten und schließen sie im selben Verlauf.
                </p>
            </div>
        </section>

        <?php if ($flash !== null): ?>
            <section class="alert alert-<?= support_h((string) ($flash['type'] ?? 'success')) ?>">
                <?= support_h((string) ($flash['message'] ?? '')) ?>
            </section>
        <?php endif; ?>

        <?php if ($dbError !== null): ?>
            <section class="alert alert-warning"><?= support_h($dbError) ?></section>
        <?php elseif (!$supportTablesReady): ?>
            <section class="alert alert-warning">
                Das Support-Modul ist strukturell vorbereitet, aber die Support-Tabellen sind noch nicht angelegt.
                Bitte führe die Migrationen aus, bevor du das Modul produktiv nutzt.
            </section>
        <?php endif; ?>

        <?php if ($supportTablesReady): ?>
            <section class="grid grid--4">
                <article class="metric"><strong><?= support_h((string) ($summary['all'] ?? 0)) ?></strong><h3>Alle Vorgänge</h3><p>Support-Anfragen im aktuellen Tenant.</p></article>
                <article class="metric"><strong><?= support_h((string) ($summary['new'] ?? 0)) ?></strong><h3>Neu</h3><p>Neue Vorgänge ohne Bearbeitung.</p></article>
                <article class="metric"><strong><?= support_h((string) ($summary['waiting_on_user'] ?? 0)) ?></strong><h3>Warten auf Antwort</h3><p>Vorgänge mit Rückfrage an Mitglieder.</p></article>
                <article class="metric"><strong><?= support_h((string) ($summary['resolved'] ?? 0)) ?></strong><h3>Erledigt</h3><p>Abgeschlossene oder gelöste Anfragen.</p></article>
            </section>

            <section class="split">
            <article class="card">
                <p class="eyebrow"><?= $isManager ? 'Neuen Vorgang anlegen' : 'Anfrage anlegen' ?></p>
                <h2>Support-Vorgang erstellen</h2>
                <form method="post" action="/support/" class="stack">
                    <input type="hidden" name="csrf" value="<?= support_h($csrf) ?>">
                    <input type="hidden" name="action" value="create-request">
                    <label>Betreff<input name="subject" maxlength="255" placeholder="Worum geht es?" required></label>
                    <label>Kategorie
                        <select name="category">
                            <?php foreach ($categories as $category): ?>
                                <option value="<?= support_h($category) ?>"><?= support_h(ucfirst(str_replace('_', ' ', $category))) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>Priorität
                        <select name="priority">
                            <?php foreach ($priorities as $priority): ?>
                                <option value="<?= support_h($priority) ?>"><?= support_h(ucfirst($priority)) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>Richtung
                        <select name="request_direction" <?= $isManager ? '' : 'disabled' ?>>
                            <?php foreach ($directions as $directionKey => $direction): ?>
                                <option value="<?= support_h($directionKey) ?>" <?= $directionKey === 'member_to_tenant' ? 'selected' : '' ?>>
                                    <?= support_h((string) ($direction['label'] ?? $directionKey)) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <?php if (!$isManager): ?>
                        <input type="hidden" name="request_direction" value="member_to_tenant">
                    <?php endif; ?>
                    <label>Nachricht<textarea name="message" placeholder="Beschreibe dein Anliegen so konkret wie möglich." required></textarea></label>
                    <div class="actions">
                        <button type="submit">Vorgang anlegen</button>
                    </div>
                </form>
            </article>

            <article class="card">
                <p class="eyebrow">Statusmodell</p>
                <h2>Bearbeitungslogik im Vorgang</h2>
                <div class="timeline">
                    <div class="timeline__item">
                        <p class="timeline__title">Neu bis in Bearbeitung</p>
                        <p class="timeline__meta">Verantwortliche setzen Status, Routing und bei Bedarf eine Zuordnung.</p>
                    </div>
                    <div class="timeline__item">
                        <p class="timeline__title">Warten auf Rückmeldung</p>
                        <p class="timeline__meta">Mitglieder können auf offene Rückfragen antworten, ohne den Vorgang zu verlieren.</p>
                    </div>
                    <div class="timeline__item">
                        <p class="timeline__title">Lösen und schließen</p>
                        <p class="timeline__meta">Jede Statusänderung landet im Verlauf und bleibt nachvollziehbar.</p>
                    </div>
                </div>
            </article>
        </section>

        <section class="card" style="margin-top:18px">
            <p class="eyebrow"><?= $isManager ? 'Alle Vorgänge' : 'Meine Vorgänge' ?></p>
            <h2><?= $isManager ? 'Tenant-Übersicht der Support-Anfragen' : 'Deine offenen und abgeschlossenen Vorgänge' ?></h2>
            <div class="table">
                <table>
                    <thead>
                        <tr>
                            <th>Nummer</th>
                            <th>Betreff</th>
                            <th>Status</th>
                            <th>Richtung</th>
                            <th>Routing</th>
                            <th>Letzte Aktivität</th>
                            <th>Dialog</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($requests as $request): ?>
                            <?php
                                $statusClass = match ((string) ($request['status'] ?? 'new')) {
                                    'new' => 'is-new',
                                    'waiting_on_user' => 'is-waiting',
                                    'resolved', 'closed' => 'is-closed',
                                    default => '',
                                };
                            ?>
                            <tr>
                                <td class="mono"><?= support_h((string) ($request['request_number'] ?? '')) ?></td>
                                <td>
                                    <strong><a href="/support/?request=<?= support_h((string) ($request['id'] ?? '')) ?>"><?= support_h((string) ($request['subject'] ?? '')) ?></a></strong>
                                    <small><?= support_h((string) ($request['category'] ?? 'general')) ?>, <?= support_h((string) ($request['priority'] ?? 'normal')) ?></small>
                                </td>
                                <td><span class="status <?= support_h($statusClass) ?>"><?= support_h((string) ($request['status'] ?? 'new')) ?></span></td>
                                <td><?= support_h((string) ($request['request_direction'] ?? 'member_to_tenant')) ?></td>
                                <td><?= support_h((string) ($request['route_target'] ?? 'tenant_responsible')) ?></td>
                                <td><?= support_dt((string) ($request['last_message_at'] ?? '')) ?></td>
                                <td><?= count((array) ($request['messages'] ?? [])) ?> Einträge</td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if ($requests === []): ?>
                            <tr>
                                <td colspan="7">Noch keine Support-Vorgänge vorhanden.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <section class="grid grid--2">
            <article class="card">
                <p class="eyebrow">Detailansicht</p>
                <h2>Ausgewählter Vorgang</h2>
                <?php if ($detailNotice !== null): ?>
                    <section class="alert alert-warning"><?= support_h((string) $detailNotice) ?></section>
                <?php endif; ?>

                <?php if (is_array($detail)): ?>
                    <div class="status-grid">
                        <div class="context">
                            <?= support_badge((string) ($detail['request_number'] ?? ''), 'success') ?>
                            <?= support_badge((string) ($detail['status'] ?? 'new'), 'warning') ?>
                            <?= support_badge((string) ($detail['route_target'] ?? 'tenant_responsible')) ?>
                        </div>
                        <p><strong>Betreff:</strong> <?= support_h((string) ($detail['subject'] ?? '')) ?></p>
                        <p><strong>Absender:</strong> <?= support_h((string) ($detail['requester_name'] ?? '')) ?> <span class="muted">(<?= support_h((string) ($detail['requester_email'] ?? '')) ?>)</span></p>
                        <p><strong>Richtung:</strong> <?= support_h((string) ($detail['request_direction'] ?? 'member_to_tenant')) ?>, <strong>Kategorie:</strong> <?= support_h((string) ($detail['category'] ?? 'general')) ?></p>
                        <p><strong>Letzte Aktivität:</strong> <?= support_dt((string) ($detail['last_message_at'] ?? '')) ?></p>
                    </div>

                    <div class="timeline" style="margin-top:18px">
                        <?php foreach (($detail['messages'] ?? []) as $message): ?>
                            <div class="timeline__item">
                                <p class="timeline__title">
                                    <?= support_h((string) ($message['author_name'] ?? 'Unbekannt')) ?>
                                    <span class="muted">· <?= support_h((string) ($message['author_role'] ?? 'member')) ?> · <?= support_dt((string) ($message['created_at'] ?? '')) ?></span>
                                </p>
                                <p class="timeline__meta"><?= nl2br(support_h((string) ($message['body'] ?? ''))) ?></p>
                                <div class="context" style="margin-top:10px">
                                    <?= support_badge((string) ($message['message_kind'] ?? 'public_reply')) ?>
                                    <?php if (!empty($message['new_status'])): ?>
                                        <?= support_badge('Status: ' . (string) $message['new_status'], 'warning') ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <?php if (($detail['messages'] ?? []) === []): ?>
                            <div class="timeline__item">
                                <p class="timeline__title">Noch kein Verlauf</p>
                                <p class="timeline__meta">Sobald geantwortet oder aktualisiert wird, erscheint hier die Historie.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <p class="muted">Wähle einen Vorgang aus der Liste, um Details, Verlauf und Bearbeitungsmöglichkeiten zu sehen.</p>
                <?php endif; ?>
            </article>

            <article class="card">
                <p class="eyebrow">Bearbeiten</p>
                <h2>Antworten und Statuswechsel</h2>

                <?php if (is_array($detail)): ?>
                    <?php if ($isManager): ?>
                        <form method="post" action="/support/" class="stack">
                            <input type="hidden" name="csrf" value="<?= support_h($csrf) ?>">
                            <input type="hidden" name="action" value="update-request">
                            <input type="hidden" name="request_id" value="<?= support_h((string) ($detail['id'] ?? '')) ?>">
                            <label>Status
                                <select name="status">
                                    <?php foreach ($statuses as $status): ?>
                                        <option value="<?= support_h($status) ?>" <?= (string) ($detail['status'] ?? '') === $status ? 'selected' : '' ?>><?= support_h($status) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </label>
                            <label>Routingziel
                                <select name="route_target">
                                    <?php foreach ($routeTargets as $routeTarget): ?>
                                        <option value="<?= support_h($routeTarget) ?>" <?= (string) ($detail['route_target'] ?? '') === $routeTarget ? 'selected' : '' ?>><?= support_h($routeTarget) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </label>
                            <label>Interne Notiz<textarea name="note" placeholder="Optional: kurze Begründung oder interner Kontext."></textarea></label>
                            <div class="actions">
                                <button type="submit">Vorgang aktualisieren</button>
                            </div>
                        </form>

                        <hr style="border:none;border-top:1px solid var(--line);margin:18px 0">
                        <form method="post" action="/support/" class="stack">
                            <input type="hidden" name="csrf" value="<?= support_h($csrf) ?>">
                            <input type="hidden" name="action" value="add-message">
                            <input type="hidden" name="request_id" value="<?= support_h((string) ($detail['id'] ?? '')) ?>">
                            <input type="hidden" name="message_kind" value="internal_note">
                            <label>Interne Antwort<textarea name="body" placeholder="Interne Rückfrage oder Zusatzinfo an das Verantwortlichen-Team."></textarea></label>
                            <div class="actions">
                                <button type="submit">Interne Notiz speichern</button>
                            </div>
                        </form>
                    <?php elseif ((string) ($detail['status'] ?? '') === 'waiting_on_user' || (string) ($detail['status'] ?? '') === 'open'): ?>
                        <form method="post" action="/support/" class="stack">
                            <input type="hidden" name="csrf" value="<?= support_h($csrf) ?>">
                            <input type="hidden" name="action" value="add-message">
                            <input type="hidden" name="request_id" value="<?= support_h((string) ($detail['id'] ?? '')) ?>">
                            <input type="hidden" name="message_kind" value="public_reply">
                            <label>Antwort<textarea name="body" placeholder="Deine Rückmeldung zum Vorgang."></textarea></label>
                            <div class="actions">
                                <button type="submit">Antwort senden</button>
                            </div>
                        </form>
                    <?php else: ?>
                        <section class="alert alert-info">
                            Für diesen Vorgang ist aktuell keine neue Antwort nötig. Sobald ein Verantwortlicher den Status auf
                            "waiting_on_user" setzt, erscheint hier wieder ein Eingabefeld.
                        </section>
                    <?php endif; ?>
                <?php else: ?>
                    <section class="alert alert-info">
                        Wähle zuerst einen Vorgang aus der Liste. Dann kannst du ihn im Detail bearbeiten oder beantworten.
                    </section>
                <?php endif; ?>
            </article>
        </section>
        <?php endif; ?>

        <p class="footer">Die Kaffeeliste | Support, Hinweise und Betriebsprozesse im Tenant-Menü</p>
    </div>
</main>
<?php if ($mobileBottomNavItems !== []): ?>
    <nav class="mobile-bottom-nav" aria-label="Mobile Kernnavigation">
        <?php foreach ($mobileBottomNavItems as $item): ?>
            <a href="<?= support_h((string) ($item['href'] ?? '/')) ?>" class="mobile-bottom-nav__link <?= (($item['key'] ?? '') === 'support') ? 'active' : '' ?>" <?= (($item['key'] ?? '') === 'support') ? 'aria-current="page"' : '' ?>>
                <span class="mobile-bottom-nav__icon"><?= match ((string) ($item['key'] ?? '')) {
                    'dashboard' => 'U',
                    'ledger' => 'B',
                    'payments' => 'Z',
                    default => '•',
                } ?></span>
                <span class="mobile-bottom-nav__label"><?= support_h((string) ($item['label'] ?? 'Link')) ?></span>
            </a>
        <?php endforeach; ?>
        <button type="button" class="mobile-bottom-nav__toggle" data-mobile-drawer-open>
            <span class="mobile-bottom-nav__icon">+</span>
            <span class="mobile-bottom-nav__label">Menü</span>
        </button>
    </nav>
<?php endif; ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const details = document.querySelectorAll('.site-more');
    const drawer = document.querySelector('[data-mobile-drawer]');
    const drawerOpeners = document.querySelectorAll('[data-mobile-drawer-open]');
    const drawerClosers = document.querySelectorAll('[data-mobile-drawer-close]');

    function closeOthers(current) {
        details.forEach(function (other) {
            if (other !== current) {
                other.open = false;
            }
        });
    }

    details.forEach(function (detail) {
        const summary = detail.querySelector('summary');
        if (summary) {
            summary.addEventListener('click', function () {
                if (!detail.open) {
                    closeOthers(detail);
                }
            });
        }

        detail.addEventListener('toggle', function () {
            if (detail.open) {
                closeOthers(detail);
            }
        });
    });

    document.querySelectorAll('.site-more__panel a, .mobile-drawer__link').forEach(function (link) {
        link.addEventListener('click', function () {
            details.forEach(function (detail) {
                detail.open = false;
            });
            if (drawer) {
                drawer.classList.remove('is-open');
                document.body.classList.remove('mobile-drawer-open');
            }
        });
    });

    if (drawer) {
        drawerOpeners.forEach(function (button) {
            button.addEventListener('click', function () {
                drawer.classList.add('is-open');
                document.body.classList.add('mobile-drawer-open');
            });
        });

        drawerClosers.forEach(function (button) {
            button.addEventListener('click', function () {
                drawer.classList.remove('is-open');
                document.body.classList.remove('mobile-drawer-open');
            });
        });
    }
});
</script>
</body>
</html>
