<?php ob_start();

// Panel-Reihenfolge aus Layout-Settings
$leftPanels  = $dashLayout['left']  ?? ['recent-posts', 'recent-pages'];
$rightPanels = $dashLayout['right'] ?? ['events', 'health', 'quick-draft', 'system'];

// Hilfsfunktion: gibt true zurück wenn Panel eingeklappt ist
$isPanelHidden = function(string $id) use ($hiddenPanels): bool {
    return in_array($id, $hiddenPanels, true);
};

// Panel-Wrapper mit Drag-Handle + Eye-Icon
$panelOpen = function(string $id, string $extraClass = '') use ($isPanelHidden): string {
    $collapsed = $isPanelHidden($id) ? ' dash-panel--collapsed' : '';
    return '<div class="dash-panel' . $collapsed . $extraClass . '" data-panel-id="' . e($id) . '">';
};

$panelHeader = function(string $id, string $iconClass, string $iconName, string $titleKey, ?string $linkHref = null, ?string $linkKey = null) use ($isPanelHidden): string {
    $collapsed  = $isPanelHidden($id);
    $eyeTitle   = $collapsed ? __('admin.dashboard.panel_expand') : __('admin.dashboard.panel_collapse');
    $eyeIcon    = $collapsed ? 'eye-off' : 'eye';
    $gripIcon   = icon('grip-vertical', 14);

    $out  = '<div class="dash-panel-header">';
    $out .= '<div class="dash-panel-header-left">';
    $out .= '<button class="dash-panel-drag-handle" title="Verschieben">' . $gripIcon . '</button>';
    $out .= '<div class="dash-panel-icon ' . e($iconClass) . '">' . icon($iconName, 14) . '</div>';
    $out .= '<h3>' . __('admin.dashboard.' . $titleKey) . '</h3>';
    $out .= '</div>';
    $out .= '<div class="dash-panel-header-right">';
    if ($linkHref && $linkKey) {
        $out .= '<a href="' . e($linkHref) . '" class="dash-panel-link">' . __('admin.dashboard.' . $linkKey) . '</a>';
    }
    $out .= '<button class="dash-panel-eye" data-panel-id="' . e($id) . '" title="' . e($eyeTitle) . '">'
          . icon($eyeIcon, 14) . '</button>';
    $out .= '</div>';
    $out .= '</div>';
    return $out;
};
?>

<!-- ── Welcome Banner ─────────────────────────────────────────────────── -->
<div class="dash-welcome">
    <div class="dash-welcome-inner">
        <div class="dash-welcome-text">
            <h2><?= __('admin.dashboard.' . $greetingKey, ['name' => e($auth->userName() ?? 'Admin')]) ?></h2>
            <p class="dash-welcome-date"><?= e($todayFormatted) ?> &mdash; <?= __('admin.dashboard.dashboard_subtitle') ?></p>
        </div>
        <div class="dash-welcome-actions">
            <a href="<?= admin_url('pages/create') ?>" class="dash-welcome-btn"><?= icon('plus', 14) ?> <?= __('admin.dashboard.new_page') ?></a>
            <a href="<?= admin_url('blog/create') ?>" class="dash-welcome-btn"><?= icon('plus', 14) ?> <?= __('admin.dashboard.new_post') ?></a>
            <a href="<?= admin_url('media') ?>" class="dash-welcome-btn"><?= icon('upload', 14) ?> <?= __('admin.dashboard.upload_media') ?></a>
        </div>
    </div>
</div>

<!-- ── Combined Updates Widget (Core + Plugins + Themes) ───────────────── -->
<?php include __DIR__ . '/_updates_widget.php'; ?>

<!-- ── Integrity Drift Alert ───────────────────────────────────────────── -->
<?php if (!empty($integrityDrift)): ?>
<div class="alert alert-danger" style="margin-bottom:1.5rem;display:flex;align-items:center;gap:.75rem;">
    <?= icon('shield-alert', 18) ?>
    <div>
        <strong><?= __('admin.marketplace.integrity_drift_title') ?></strong>
        <?= e($integrityDrift) ?>
        &mdash; <a href="<?= admin_url('marketplace/audit-log') ?>"><?= __('admin.marketplace_audit.title') ?></a>
    </div>
</div>
<?php endif; ?>

<!-- ── Content Area ─────────────────────────────────────────────────── -->
<div class="dash-content-area">

    <!-- ── Primary Stats ─────────────────────────────────────────────── -->
    <div class="dash-stats-primary">
        <a href="<?= admin_url('pages') ?>" class="dash-stat-card">
            <div class="dash-stat-top">
                <div class="dash-stat-icon dash-stat-icon--pages"><?= icon('file-text', 20) ?></div>
            </div>
            <div class="dash-stat-number"><?= (int) $pageCount ?></div>
            <div class="dash-stat-label"><?= __('admin.dashboard.pages') ?></div>
            <?php if (($pagesScheduled ?? 0) > 0): ?>
            <div class="dash-stat-sub">
                <span class="badge badge-warning"><?= (int) $pagesScheduled ?> <?= __('admin.dashboard.scheduled') ?></span>
            </div>
            <?php endif; ?>
        </a>
        <a href="<?= admin_url('blog') ?>" class="dash-stat-card">
            <div class="dash-stat-top">
                <div class="dash-stat-icon dash-stat-icon--blog"><?= icon('pen-line', 20) ?></div>
            </div>
            <div class="dash-stat-number"><?= (int) $postCount ?></div>
            <div class="dash-stat-label"><?= __('admin.dashboard.blog_posts') ?></div>
            <div class="dash-stat-sub">
                <span class="badge badge-success"><?= (int) $postPublished ?> <?= __('admin.dashboard.published') ?></span>
                <span class="badge badge-draft"><?= (int) $postDraft ?> <?= __('admin.dashboard.draft') ?></span>
                <?php if (($postScheduled ?? 0) > 0): ?>
                <span class="badge badge-warning"><?= (int) $postScheduled ?> <?= __('admin.dashboard.scheduled') ?></span>
                <?php endif; ?>
            </div>
        </a>
        <a href="<?= admin_url('gallery') ?>" class="dash-stat-card">
            <div class="dash-stat-top">
                <div class="dash-stat-icon dash-stat-icon--gallery"><?= icon('image', 20) ?></div>
            </div>
            <div class="dash-stat-number"><?= (int) $galleryCount ?></div>
            <div class="dash-stat-label"><?= __('admin.dashboard.gallery_albums') ?></div>
        </a>
        <a href="<?= admin_url('events') ?>" class="dash-stat-card">
            <div class="dash-stat-top">
                <div class="dash-stat-icon dash-stat-icon--events"><?= icon('calendar', 20) ?></div>
            </div>
            <div class="dash-stat-number"><?= (int) $eventCount ?></div>
            <div class="dash-stat-label"><?= __('admin.dashboard.events') ?></div>
            <?php if ($upcomingEventCount > 0): ?>
            <div class="dash-stat-sub">
                <span class="badge badge-warning"><?= (int) $upcomingEventCount ?> <?= __('admin.dashboard.upcoming') ?></span>
            </div>
            <?php endif; ?>
        </a>
    </div>

    <!-- ── Secondary Stats ───────────────────────────────────────────── -->
    <div class="dash-stats-secondary">
        <a href="<?= admin_url('downloads') ?>" class="dash-stat-mini">
            <div class="dash-stat-mini-icon"><?= icon('download', 16) ?></div>
            <div>
                <span class="dash-stat-mini-num"><?= (int) $downloadCount ?></span>
                <span class="dash-stat-mini-label"><?= __('admin.dashboard.downloads') ?></span>
            </div>
        </a>
        <a href="<?= admin_url('media') ?>" class="dash-stat-mini dash-stat-mini--storage">
            <div class="dash-stat-mini-icon"><?= icon('hard-drive', 16) ?></div>
            <div class="dash-stat-mini-info">
                <span class="dash-stat-mini-num"><?= (int) $mediaCount ?></span>
                <span class="dash-stat-mini-label"><?= __('admin.dashboard.media_files') ?></span>
                <div class="dash-storage-bar-wrap">
                    <div class="dash-storage-bar">
                        <div class="dash-storage-bar-fill" style="width:<?= min(100, (int) $storageInfo['used_pct']) ?>%"></div>
                    </div>
                    <div class="dash-storage-bar-label">
                        <span><?= e($storageInfo['used_fmt']) ?></span>
                        <span><?= e($storageInfo['total_fmt']) ?></span>
                    </div>
                </div>
            </div>
        </a>
        <a href="<?= admin_url('plugins') ?>" class="dash-stat-mini">
            <div class="dash-stat-mini-icon"><?= icon('puzzle', 16) ?></div>
            <div>
                <span class="dash-stat-mini-num"><?= (int) $activePluginCount ?></span>
                <span class="dash-stat-mini-label"><?= __('admin.dashboard.plugins_active') ?></span>
            </div>
        </a>
        <a href="<?= admin_url('users') ?>" class="dash-stat-mini">
            <div class="dash-stat-mini-icon"><?= icon('users', 16) ?></div>
            <div>
                <span class="dash-stat-mini-num"><?= (int) $userCount ?></span>
                <span class="dash-stat-mini-label"><?= __('admin.dashboard.users') ?></span>
            </div>
        </a>
    </div>

    <!-- ── Content Grid ───────────────────────────────────────────────── -->
    <div class="dash-content-grid">

        <!-- Left Column -->
        <div class="dash-content-col" id="dash-col-left" data-col="left">
        <?php foreach ($leftPanels as $panelId):
            switch ($panelId):

                case 'recent-posts': ?>
                <?= $panelOpen($panelId) ?>
                <?= $panelHeader($panelId, 'dash-panel-icon--posts', 'pen-line', 'recent_posts', admin_url('blog'), 'view_all_posts') ?>
                <?php if (empty($recentPosts)): ?>
                    <p class="dash-panel-empty"><?= __('admin.dashboard.recent_posts_empty') ?></p>
                <?php else: ?>
                    <div class="dash-panel-body">
                        <?php foreach ($recentPosts as $post): ?>
                        <div class="dash-list-item">
                            <a href="<?= admin_url('blog/edit/' . (int) $post['id']) ?>" class="dash-list-title"><?= e($post['title']) ?></a>
                            <span class="dash-list-meta">
                                <span class="badge <?= $post['status'] === 'published' ? 'badge-success' : 'badge-draft' ?>"><?= e($post['status']) ?></span>
                                <span class="dash-list-date"><?= date('d.m.Y', strtotime($post['created_at'])) ?></span>
                            </span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                </div>
                <?php break;

                case 'recent-pages': ?>
                <?= $panelOpen($panelId) ?>
                <?= $panelHeader($panelId, 'dash-panel-icon--pages', 'file-text', 'recent_pages', admin_url('pages'), 'view_all_pages') ?>
                <?php if (empty($recentPages)): ?>
                    <p class="dash-panel-empty"><?= __('admin.dashboard.recent_pages_empty') ?></p>
                <?php else: ?>
                    <div class="dash-panel-body">
                        <?php foreach ($recentPages as $page): ?>
                        <div class="dash-list-item">
                            <a href="<?= admin_url('pages/edit/' . (int) $page['id']) ?>" class="dash-list-title"><?= e($page['title']) ?></a>
                            <span class="dash-list-meta">
                                <span class="badge <?= $page['status'] === 'published' ? 'badge-success' : 'badge-draft' ?>"><?= e($page['status']) ?></span>
                                <span class="dash-list-date"><?= date('d.m.Y', strtotime($page['updated_at'])) ?></span>
                            </span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                </div>
                <?php break;

            endswitch;
        endforeach; ?>
        </div><!-- /left col -->

        <!-- Right Column -->
        <div class="dash-content-col" id="dash-col-right" data-col="right">
        <?php foreach ($rightPanels as $panelId):
            switch ($panelId):

                case 'events': ?>
                <?= $panelOpen($panelId) ?>
                <?= $panelHeader($panelId, 'dash-panel-icon--events', 'calendar', 'upcoming_events', admin_url('events'), 'view_all_events') ?>
                <?php if (empty($upcomingEvents)): ?>
                    <div class="dash-panel-empty-state">
                        <div class="dash-empty-icon"><?= icon('calendar', 22) ?></div>
                        <p><?= __('admin.dashboard.upcoming_events_empty') ?></p>
                        <a href="<?= admin_url('events/create') ?>" class="btn btn-sm btn-primary"><?= icon('plus', 12) ?> <?= __('admin.dashboard.create_event') ?></a>
                    </div>
                <?php else: ?>
                    <div class="dash-panel-body">
                        <?php foreach ($upcomingEvents as $ev): ?>
                        <div class="dash-event-item">
                            <div class="dash-event-date-block">
                                <span class="dash-event-day"><?= date('d', strtotime($ev['start_date'])) ?></span>
                                <span class="dash-event-month"><?= date('M', strtotime($ev['start_date'])) ?></span>
                            </div>
                            <div class="dash-event-info">
                                <a href="<?= admin_url('events/edit/' . (int) $ev['id']) ?>" class="dash-event-title"><?= e($ev['title']) ?></a>
                                <?php if (!empty($ev['start_time'])): ?>
                                    <span class="dash-event-time"><?= date('H:i', strtotime($ev['start_time'])) ?> Uhr</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                </div>
                <?php break;

                case 'health': ?>
                <?= $panelOpen($panelId) ?>
                <div class="dash-panel-header">
                    <div class="dash-panel-header-left">
                        <button class="dash-panel-drag-handle" title="Verschieben"><?= icon('grip-vertical', 14) ?></button>
                        <div class="dash-health-score dash-health-score--<?= e($healthClass) ?>"><?= (int) $healthScore ?>%</div>
                        <div>
                            <div style="font-size:0.8125rem;font-weight:600;color:var(--gray-700)"><?= __('admin.dashboard.health_title') ?></div>
                            <div style="font-size:0.6875rem;color:var(--gray-400)">
                                <?php if ($healthIssueCount === 0): ?>
                                    <?= __('admin.dashboard.health_issues_none') ?>
                                <?php else: ?>
                                    <?= __('admin.dashboard.health_issues_count', ['count' => $healthIssueCount]) ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="dash-panel-header-right">
                        <button class="dash-panel-eye" data-panel-id="health" title="<?= e(__('admin.dashboard.' . ($isPanelHidden('health') ? 'panel_expand' : 'panel_collapse'))) ?>"><?= icon($isPanelHidden('health') ? 'eye-off' : 'eye', 14) ?></button>
                    </div>
                </div>
                <ul class="dash-health-items">
                    <?php foreach ($healthIssues as $issue): ?>
                    <li class="dash-health-item">
                        <span class="dash-health-dot dash-health-dot--<?= $issue['type'] === 'ok' ? 'green' : 'amber' ?>"></span>
                        <?php if ($issue['link']): ?>
                            <a href="<?= e($issue['link']) ?>" class="dash-health-label"><?= e($issue['label']) ?></a>
                        <?php else: ?>
                            <span class="dash-health-label"><?= e($issue['label']) ?></span>
                        <?php endif; ?>
                        <?php if ($issue['action'] === 'fix' && $issue['link']): ?>
                            <a href="<?= e($issue['link']) ?>" class="dash-health-action"><?= __('admin.dashboard.health_fix') ?></a>
                        <?php elseif ($issue['action'] === 'create' && $issue['link']): ?>
                            <form method="POST" action="<?= e($issue['link']) ?>" style="display:inline"><?= csrf_field() ?><button type="submit" class="dash-health-action" style="background:none;border:none;cursor:pointer;padding:0;font:inherit;color:inherit;text-decoration:underline"><?= __('admin.dashboard.health_create') ?></button></form>
                        <?php elseif ($issue['action']): ?>
                            <span class="dash-health-action"><?= __('admin.dashboard.health_' . e($issue['action'])) ?></span>
                        <?php else: ?>
                            <span class="dash-health-ok"><?= __('admin.dashboard.health_ok') ?></span>
                        <?php endif; ?>
                    </li>
                    <?php endforeach; ?>
                    <?php if (empty($healthIssues)): ?>
                    <li class="dash-health-item">
                        <span class="dash-health-dot dash-health-dot--green"></span>
                        <span class="dash-health-label"><?= __('admin.dashboard.health_issues_none') ?></span>
                        <span class="dash-health-ok"><?= __('admin.dashboard.health_ok') ?></span>
                    </li>
                    <?php endif; ?>
                </ul>
                </div>
                <?php break;

                case 'accessibility': ?>
                <?php if (!empty($a11yEnabled)): ?>
                <?= $panelOpen($panelId) ?>
                <?= $panelHeader($panelId, 'dash-panel-icon--a11y', 'accessibility', 'a11y_title') ?>
                <?php if (empty($a11yIssues)): ?>
                <ul class="dash-health-items">
                    <li class="dash-health-item">
                        <span class="dash-health-dot dash-health-dot--green"></span>
                        <span class="dash-health-label"><?= __('admin.dashboard.a11y_no_issues') ?></span>
                        <span class="dash-health-ok"><?= __('admin.dashboard.health_ok') ?></span>
                    </li>
                </ul>
                <?php else: ?>
                <?php
                    $a11yTotal = count($a11yIssues);
                    $a11yGrouped = [];
                    foreach (array_slice($a11yIssues, 0, 20) as $ai) {
                        $a11yGrouped[$ai['type']] = ($a11yGrouped[$ai['type']] ?? 0) + 1;
                    }
                ?>
                <ul class="dash-health-items">
                    <li class="dash-health-item">
                        <span class="dash-health-dot dash-health-dot--amber"></span>
                        <span class="dash-health-label" style="color:var(--gray-500)">
                            <?= __('admin.dashboard.a11y_issues_found' . ($a11yTotal === 1 ? '_1' : ''), ['count' => $a11yTotal]) ?>
                        </span>
                    </li>
                    <?php foreach ($a11yGrouped as $aType => $aCount): ?>
                    <li class="dash-health-item">
                        <span class="dash-health-dot dash-health-dot--amber"></span>
                        <span class="dash-health-label"><?= $aCount ?> <?= __('admin.dashboard.a11y_' . $aType . ($aCount === 1 ? '_1' : '')) ?></span>
                    </li>
                    <?php endforeach; ?>
                    <?php
                    $shown = 0;
                    foreach ($a11yIssues as $ai):
                        if ($shown >= 5) break;
                    ?>
                    <li class="dash-health-item">
                        <span class="dash-health-dot" style="visibility:hidden"></span>
                        <span class="dash-health-label" style="color:var(--gray-400);font-size:0.75rem;"><?= e($ai['entity_title'] ?? '') ?>: <?= e($ai['label']) ?></span>
                        <a href="<?= e($ai['link']) ?>" class="dash-health-action"><?= __('admin.common.edit') ?></a>
                    </li>
                    <?php $shown++; endforeach; ?>
                </ul>
                <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php break;

                case 'quick-draft': ?>
                <?= $panelOpen($panelId) ?>
                <?= $panelHeader($panelId, 'dash-panel-icon--draft', 'pen-line', 'quick_draft_title') ?>
                <div class="dash-quick-draft">
                    <form method="POST" action="<?= admin_url('dashboard/quick-draft') ?>" id="quick-draft-form">
                        <?= csrf_field() ?>
                        <input type="text" name="title" class="dash-qd-input" placeholder="<?= e(__('admin.dashboard.quick_draft_placeholder_title')) ?>" required autocomplete="off">
                        <textarea name="content" class="dash-qd-textarea" placeholder="<?= e(__('admin.dashboard.quick_draft_placeholder_content')) ?>"></textarea>
                        <div class="dash-qd-footer">
                            <div class="dash-qd-type">
                                <label class="dash-qd-type-label">
                                    <input type="radio" name="type" value="blog" checked> <?= __('admin.dashboard.quick_draft_type_post') ?>
                                </label>
                                <label class="dash-qd-type-label">
                                    <input type="radio" name="type" value="page"> <?= __('admin.dashboard.quick_draft_type_page') ?>
                                </label>
                            </div>
                            <button type="submit" class="btn btn-sm btn-primary"><?= __('admin.dashboard.quick_draft_save') ?></button>
                        </div>
                    </form>
                </div>
                </div>
                <?php break;

                case 'system': ?>
                <?= $panelOpen($panelId) ?>
                <?= $panelHeader($panelId, 'dash-panel-icon--system', 'monitor', 'system_info', admin_url('system'), 'view_system_status') ?>
                <div class="dash-panel-body">
                    <div class="dash-system-grid">
                        <div class="dash-system-item">
                            <dt><?= __('admin.dashboard.cms_version') ?></dt>
                            <dd><strong><?= e($systemInfo['cms_version']) ?></strong></dd>
                        </div>
                        <div class="dash-system-item">
                            <dt><?= __('admin.dashboard.php_version') ?></dt>
                            <dd><?= e($systemInfo['php_version']) ?></dd>
                        </div>
                        <div class="dash-system-item">
                            <dt><?= __('admin.dashboard.active_theme') ?></dt>
                            <dd><a href="<?= admin_url('themes') ?>" class="dash-system-link"><?= e(ucfirst($systemInfo['active_theme'])) ?></a></dd>
                        </div>
                        <div class="dash-system-item">
                            <dt><?= __('admin.dashboard.maintenance_mode') ?></dt>
                            <dd>
                                <?php if ($systemInfo['maintenance']): ?>
                                    <a href="<?= admin_url('maintenance') ?>" class="badge badge-warning"><?= __('admin.dashboard.maintenance_active') ?></a>
                                <?php else: ?>
                                    <span class="badge badge-success"><?= __('admin.dashboard.maintenance_inactive') ?></span>
                                <?php endif; ?>
                            </dd>
                        </div>
                    </div>
                </div>
                </div>
                <?php break;

            endswitch;
        endforeach; ?>
        </div><!-- /right col -->

    </div><!-- /content-grid -->

    <!-- ── What's New Banner ─────────────────────────────────────────── -->
    <div class="dash-news-banner" id="dash-news-banner">
        <div class="dash-news-icon"><?= icon('sparkles', 16) ?></div>
        <div class="dash-news-body">
            <strong><?= __('admin.dashboard.whats_new_title', ['version' => e($cmsVersion)]) ?></strong>
            <ul>
                <li>Lucide Icon-Picker (132 Icons)</li>
                <li>Frontend-Suche</li>
                <li>Blog: Lesezeit, ToC, Verwandte Posts</li>
                <li>Bulk Actions in Admin-Listen</li>
                <li>Dashboard Redesign</li>
            </ul>
        </div>
        <button class="dash-news-close" id="dash-news-close" title="Schließen">&times;</button>
    </div>

</div><!-- /dash-content-area -->

<!-- CSRF-Token für AJAX -->
<input type="hidden" id="dash-csrf-token" value="<?= e($csrf->token()) ?>">

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
