<?php
/**
 * 页面框架：页头 / 页脚 / 提示
 */

function render_flashes()
{
    foreach (take_flashes() as $f) {
        $cls = $f['type'] === 'err' ? 'toast err' : 'toast';
        echo '<div class="' . $cls . '">' . e($f['msg']) . '</div>';
    }
}

function render_header($title = '', array $opts = [])
{
    $siteName = setting('site_name', '木漏茶室');
    $logo = setting('site_logo', 'assets/img/logo.svg');
    $favicon = site_favicon_url($logo);
    $me = current_user();
    $pageName = $GLOBALS['PAGE'] ?? 'home';
    $fullTitle = $title ? ($title . ' · ' . $siteName) : $siteName;

    $pmUnread = $me ? (int) DB::val(
        'SELECT COUNT(*) FROM ' . DB::table('messages') . ' WHERE to_id = ? AND is_read = 0',
        [$me['id']],
        0
    ) : 0;
    $ntUnread = $me ? (int) DB::val(
        'SELECT COUNT(*) FROM ' . DB::table('notifications') . ' WHERE user_id = ? AND is_read = 0',
        [$me['id']],
        0
    ) : 0;
    $imp = impersonating();
    $themeLibrary = site_theme_library();
    $activeTheme = setting('theme_mode', 'default');
    if (!site_theme_find($activeTheme)) {
        $activeTheme = 'default';
    }
    $fixedSkins = site_theme_fixed_keys();
    $activeFontKey = setting('font_family', 'default');
    $fontFaceCss = site_font_face_css($activeFontKey);
    $customThemeCss = site_theme_custom_css();
    $deviceMode = device_view_mode();
    // 用户已经显式选择过浏览模式时，前端不再按 UA 自动改回手机端。
    $hasDevicePref = isset($_COOKIE['km_device_view']) || isset($_GET['device']);
    // 电脑端 / 平板端必须同步切换布局视口，否则手机上仍会套用手机媒体查询。
    if ($deviceMode === 'desktop') {
        $viewportContent = 'width=1200';
    } elseif ($deviceMode === 'tablet') {
        $viewportContent = 'width=900';
    } else {
        $viewportContent = 'width=device-width, initial-scale=1, viewport-fit=cover';
    }
    ?>
<!DOCTYPE html>
<html lang="<?= e(km_html_lang()) ?>" data-theme="<?= e($activeTheme) ?>" data-device-mode="<?= e($deviceMode) ?>" style="--font:<?= e(site_font_stack($activeFontKey)) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="<?= e($viewportContent) ?>">
<script>
(function () {
  try {
    if (<?= $hasDevicePref ? 'true' : 'false' ?>) return;
    if (document.documentElement.getAttribute('data-device-mode') !== 'desktop') return;
    var ua = navigator.userAgent || '';
    var platform = navigator.platform || '';
    var touchPoints = navigator.maxTouchPoints || 0;
    var shortSide = window.screen ? Math.min(window.screen.width || 0, window.screen.height || 0) : 0;
    var isPhone = /iphone|ipod|android/i.test(ua) || /iphone|ipod|android/i.test(platform);
    var isSmallScreen = shortSide > 0 && shortSide < 760;
    var isTouchPhone = touchPoints > 0 && shortSide > 1000 && shortSide < 1300;
    var isAppleTouch = touchPoints > 0 && /macintosh|mac os x|macintel|iphone|ipad|ipod/i.test(ua + ' ' + platform);
    if (isPhone || isSmallScreen || isTouchPhone || isAppleTouch) {
      document.documentElement.setAttribute('data-device-mode', 'mobile');
      var vp = document.querySelector('meta[name="viewport"]');
      if (vp) vp.setAttribute('content', 'width=device-width, initial-scale=1, viewport-fit=cover');
      document.cookie = 'km_device_view=mobile; path=<?= e(BASE_PATH !== '' ? BASE_PATH . '/' : '/') ?>; max-age=31536000; samesite=lax';
      window.__KM_DEVICE_AUTO_MOBILE__ = true;
      try {
        if (!sessionStorage.getItem('km_device_mobile_reload')) {
          sessionStorage.setItem('km_device_mobile_reload', '1');
          location.reload();
          return;
        }
      } catch (e) {
        location.reload();
        return;
      }
    }
  } catch (e) {}
})();
</script>
<meta name="theme-color" content="<?= $activeTheme === 'qinglan' ? '#f1f6f1' : '#eaf5fc' ?>">
<title><?= e($fullTitle) ?></title>
<meta name="description" content="<?= e(setting('site_intro', '一室茶香，半窗霜雪。')) ?>">
<?php if (setting('seo_enable', '1') === '1'):
  $canonical = full_url($_SERVER['REQUEST_URI'] ?? ('/' . basename($_SERVER['SCRIPT_NAME'] ?? 'index.php')));
  $ogImage = full_url(site_logo_favicon($logo));
  $noindex = in_array($pageName, ['admin', 'login', 'register', 'forgot', 'verify_email'], true);
?>
<link rel="canonical" href="<?= e($canonical) ?>">
<?php if ($noindex): ?><meta name="robots" content="noindex,nofollow"><?php endif; ?>
<meta property="og:site_name" content="<?= e($siteName) ?>">
<meta property="og:title" content="<?= e($fullTitle) ?>">
<meta property="og:description" content="<?= e(setting('site_intro', '一室茶香，半窗霜雪。')) ?>">
<meta property="og:type" content="website">
<meta property="og:url" content="<?= e($canonical) ?>">
<meta property="og:image" content="<?= e($ogImage) ?>">
<meta name="twitter:card" content="summary_large_image">
<link rel="alternate" type="application/rss+xml" title="<?= e($siteName) ?> RSS" href="<?= e(base_url('rss.php')) ?>">
<?php endif; ?>
<style id="driveAudioCardCritical">
/* 详情音频卡：内联兜底，避免 iOS/Safari 继续吃旧缓存 */
.drive-audio-card .km-audio{display:grid!important;grid-template-columns:58px minmax(0,1fr)!important;align-items:start!important;gap:10px!important;padding:12px!important;border-radius:18px!important;max-width:560px}
.drive-audio-card .km-audio-cover{width:58px!important;height:58px!important;flex-basis:58px!important;border-radius:14px!important}
.drive-audio-card .km-audio-main{gap:8px!important;min-width:0}
.drive-audio-card .km-audio-wave,.drive-audio-card .km-audio-caption{display:none!important}
.drive-audio-card .km-audio-title{font-size:15.5px!important;line-height:1.3!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important}
.drive-audio-card .km-audio-progress{width:100%!important;min-width:0}
.drive-audio-card .km-audio-actions{gap:10px!important;margin-top:2px!important}
.drive-audio-card .km-audio-play{width:40px!important;height:40px!important;flex:0 0 40px!important}
.drive-audio-card .km-audio-download{height:40px!important;min-width:92px!important;padding:0 16px!important;border-radius:999px!important}
.drive-audio-card .km-audio>audio{position:absolute!important;width:1px!important;height:1px!important;opacity:0!important;pointer-events:none!important;clip-path:inset(50%)!important}
.drive-audio-card .km-audio.is-error>audio{position:static!important;width:100%!important;height:auto!important;opacity:1!important;pointer-events:auto!important;clip-path:none!important}
@media(max-width:520px){
 .drive-audio-card .km-audio{grid-template-columns:52px minmax(0,1fr)!important;gap:9px!important;padding:11px!important}
 .drive-audio-card .km-audio-cover{width:52px!important;height:52px!important;flex-basis:52px!important}
 .drive-audio-card .km-audio-title{font-size:14.5px!important}
 .drive-audio-card .km-audio-download{height:38px!important;min-width:84px!important;padding:0 14px!important}
}
</style>
<?php if (setting('pwa_enable', '1') === '1'): ?>
<link rel="manifest" href="<?= e(base_url('manifest.php')) ?>">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="<?= e($siteName) ?>">
<link rel="apple-touch-icon" href="<?= e(full_url(site_logo_favicon($logo))) ?>">
<?php endif; ?>
<link rel="icon" href="<?= e($favicon) ?>">
<link rel="stylesheet" href="<?= e(asset('css/app.css')) ?>">
<?php if ($deviceMode === 'mobile' || $deviceMode === 'desktop'): ?><link rel="stylesheet" href="<?= e(asset('css/mobile-mode.css')) ?>"><?php endif; ?>
<link rel="stylesheet" href="<?= e(asset('css/netdisk-baidu.css')) ?>">
<script>
(function(){
  function kmTouchLayout(){
    try {
      var d = document.documentElement;
      var iw = window.innerWidth || 0;
      var sw = (window.screen && screen.width) || 0;
      var touch = navigator.maxTouchPoints || 0;
      var ua = (navigator.userAgent || '').toLowerCase();
      var isIOS = /iphone|ipad|ipod/.test(ua) || (navigator.platform === 'MacIntel' && touch > 1);
      if (touch > 0 && iw > 760 && isIOS) {
        // 关键：苹果桌面模式服务端给的是电脑版两栏布局，必须切回 mobile 才会变单列。
        d.setAttribute('data-device-mode', 'mobile');
        d.classList.add('km-touch-wide');
        d.classList.remove('km-touch-full');
        var ratio = sw > 0 ? iw / sw : 1;
        if (iw >= 900 && iw <= 1010) ratio = Math.max(ratio, 2.5);
        if (ratio > 1.15) d.style.setProperty('--km-touch-scale', String(Math.min(3, ratio)));
        else d.style.removeProperty('--km-touch-scale');
      } else if (touch > 0 && iw > 760 && iw >= 900 && iw <= 1010) {
        // 安卓桌面画布同样切手机单列；只解除 430px 上限，绝不套苹果的放大倍率。
        d.setAttribute('data-device-mode', 'mobile');
        d.classList.add('km-touch-full');
        d.classList.remove('km-touch-wide');
        d.style.removeProperty('--km-touch-scale');
      } else {
        d.classList.remove('km-touch-wide', 'km-touch-full');
        d.style.removeProperty('--km-touch-scale');
      }
    } catch (e) {}
  }
  kmTouchLayout();
  window.addEventListener('resize', kmTouchLayout, {passive:true});
  window.addEventListener('orientationchange', function(){ setTimeout(kmTouchLayout, 150); });
})();
</script>
<?php if ($fontFaceCss !== ''): ?><style><?= $fontFaceCss ?></style><?php endif; ?>
<?php foreach ($customThemeCss as $themeKey => $themeCss): ?>
<link rel="stylesheet" href="<?= e(upload_url($themeCss)) ?>" data-km-theme-css="<?= e($themeKey) ?>">
<?php endforeach; ?>
<script>
(function(){
  try {
    var t = localStorage.getItem('km-theme');
    var adminTheme = <?= json_encode($activeTheme) ?>;
    var fixedSkins = <?= json_encode($fixedSkins) ?>;
    if (t && fixedSkins.indexOf(adminTheme) === -1 && <?= json_encode(array_column($themeLibrary, 'key')) ?>.indexOf(t) !== -1) {
      document.documentElement.setAttribute('data-theme', t);
    }
    window.KM_THEMES = <?= json_encode(array_column($themeLibrary, 'key')) ?>;
  } catch (e) {}
})();
</script>
<?php if (setting('pwa_enable', '1') === '1'): ?>
<script>if ('serviceWorker' in navigator) { window.addEventListener('load', function () { navigator.serviceWorker.register('<?= e(base_url('sw.js')) ?>?v=<?= e(APP_VERSION) ?>').then(function (r) { if (r && r.update) r.update(); }).catch(function () {}); }); }</script>
<?php endif; ?>
</head>
<body class="page-<?= e($pageName) ?>">
<?php $bgCustom = trim((string) setting('site_bg_image', '')); ?>
<div class="bg-layer<?= $bgCustom !== '' ? ' has-custom' : '' ?>" aria-hidden="true"<?= $bgCustom !== '' ? ' style="--site-bg:url(\'' . e(upload_url($bgCustom)) . '\')"' : '' ?>>
  <div class="bg-glow g1"></div>
  <div class="bg-glow g2"></div>
  <div class="bg-snow"></div>
</div>

<?php if ($imp): ?>
<div class="imp-bar">
  <span>正在以 <b><?= e(display_name($me)) ?></b> 的身份浏览</span>
  <a href="<?= e(page_url('home', ['act' => 'stop_impersonate'])) ?>">退出代登录</a>
</div>
<?php endif; ?>
<?php if (is_admin(current_user()) && setting('maintenance') === '1'): ?>
<div class="maint-bar">站点处于维护模式，仅管理员可见完整内容 · <a href="<?= e(page_url('admin', ['s' => 'settings_security'])) ?>">去设置</a></div>
<?php endif; ?>

<header class="site-header">
  <div class="header-inner">
    <a class="brand" href="<?= e(page_url('home')) ?>">
      <?= site_logo_html($logo, 'brand-logo') ?>
      <span class="brand-text">
        <strong><?= e($siteName) ?></strong>
        <small><?= e(setting('site_intro', '木漏れ日 · 茶室')) ?></small>
      </span>
    </a>

    <nav class="top-nav">
      <a class="<?= $pageName === 'home' ? 'on' : '' ?>" href="<?= e(page_url('home')) ?>"><?= e(t('home', '首页')) ?></a>
      <a class="<?= $pageName === 'extensions' ? 'on' : '' ?>" href="<?= e(page_url('extensions')) ?>"><?= e(t('extensions', '扩展中心')) ?></a>
      <a class="<?= $pageName === 'compose' ? 'on' : '' ?>" href="<?= e(page_url('compose')) ?>"><?= e(t('compose', '发帖')) ?></a>
      <a class="<?= $pageName === 'world' ? 'on' : '' ?>" href="<?= e(page_url('world')) ?>"><?= e(t('world', '世界圈')) ?></a>
      <a class="<?= $pageName === 'links' ? 'on' : '' ?>" href="<?= e(page_url('links')) ?>"><?= e(t('links', '友情链接')) ?></a>
    </nav>

    <div class="header-actions">
      <button class="icon-btn theme-toggle" type="button" aria-label="切换主题" onclick="KM.toggleTheme()">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="12" r="4.2"/><path d="M12 2v2.4M12 19.6V22M2 12h2.4M19.6 12H22M4.6 4.6l1.7 1.7M17.7 17.7l1.7 1.7M19.4 4.6l-1.7 1.7M6.3 17.7L4.6 19.4"/></svg>
      </button>
      <?php if ($me): ?>
        <a class="icon-btn" href="<?= e(page_url('friends')) ?>" aria-label="好友和私信" title="好友和私信">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.4"/><path d="M3 19c.8-3.2 3-5 6-5s5.2 1.8 6 5"/><path d="M15 14c2.5.2 4.3 1.8 5 4.4"/></svg>
          <?php if ($pmUnread): ?><i class="badge"><?= $pmUnread > 99 ? '99+' : $pmUnread ?></i><?php endif; ?>
        </a>
        <a class="icon-btn" href="<?= e(page_url('notifications')) ?>" aria-label="通知">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M6 16V10a6 6 0 0112 0v6l2 2H4l2-2z"/><path d="M9.5 20a2.5 2.5 0 005 0"/></path></svg>
          <?php if ($ntUnread): ?><i class="badge"><?= $ntUnread > 99 ? '99+' : $ntUnread ?></i><?php endif; ?>
        </a>
        <a class="icon-btn logout-btn" href="<?= e(page_url('logout')) ?>" aria-label="退出登录" title="退出登录">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M10 4H6a2 2 0 00-2 2v12a2 2 0 002 2h4"/><path d="M15 8l4 4-4 4"/><path d="M19 12H9"/></svg>
        </a>
        <a class="avatar-link" href="<?= e(page_url('profile')) ?>" title="<?= e(display_name($me)) ?>">
          <?= avatar_html($me) ?>
        </a>
        <?php if (is_admin(current_user())): ?>
          <a class="admin-entry" href="<?= e(page_url('admin')) ?>"><?= e(t('admin', '后台')) ?></a>
        <?php endif; ?>
      <?php else: ?>
        <a class="btn-mini" href="<?= e(page_url('login')) ?>"><?= e(t('login', '登录')) ?></a>
        <?php if (setting('register_open', '1') === '1'): ?>
        <a class="btn-mini ghost" href="<?= e(page_url('register')) ?>"><?= e(t('register', '注册')) ?></a>
        <?php endif; ?>
      <?php endif; ?>
    </div>
  </div>
  <?php $stickyHtml = trim((string) setting('sticky_html', '')); ?>
  <?php if ($stickyHtml !== ''): ?>
  <div class="sticky-html"><?= $stickyHtml ?></div>
  <?php endif; ?>
  <?php $homeStickyHtml = trim((string) setting('home_sticky_html', '')); ?>
  <?php if ($homeStickyHtml !== '' && $pageName === 'home'): ?>
  <div class="sticky-html home-sticky-html"><?= $homeStickyHtml ?></div>
  <?php endif; ?>
</header>

<?php
    $headerHtml = setting('header_html', '');
    if ($headerHtml !== '' && $pageName === 'home'):
?>
<div class="header-html"><?= $headerHtml ?></div>
<?php endif; ?>

<main class="wrap">
<?php render_flashes(); ?>
<?php
}

/**
 * 云先森音乐播放器兼容：
 * 同一页面只允许一个 <yxs-music-player> 宿主，重复宿主会被组件直接忽略；
 * 同时把错误的相对 api-url 修正为官方云端接口，避免首页出现“播放器云端数据加载失败”。
 */
function km_music_player_html_detect($html)
{
    return stripos((string) $html, 'yxs-music-player') !== false
        || stripos((string) $html, 'music-player.min.js') !== false;
}

function km_music_player_html_normalize($html)
{
    $html = (string) $html;
    // 云先森播放器的相对 api-url 在站内会 404，统一补成官方云端地址；
    // 官方接口要求域名先在 pinpinping.cn/auth/ 完成授权，否则会返回 403。
    $html = preg_replace_callback(
        '/(<yxs-music-player\b[^>]*\bapi-url\s*=\s*["\'])(?:https?:\/\/www\.pinpinping\.cn)?\/api\/v1\/music\/top\?([^"\']*)(["\'])/i',
        function ($m) {
            parse_str(html_entity_decode($m[2], ENT_QUOTES | ENT_HTML5, 'UTF-8'), $query);
            $platform = strtolower((string) ($query['platform'] ?? 'netease'));
            if (!preg_match('/^[a-z0-9_\-]{1,30}$/', $platform)) {
                $platform = 'netease';
            }
            $topId = preg_replace('/[^0-9]/', '', (string) ($query['topId'] ?? '3778678'));
            if ($topId === '') {
                $topId = '3778678';
            }
            $api = 'https://www.pinpinping.cn/api/v1/music/top?platform=' . rawurlencode($platform) . '&topId=' . rawurlencode($topId);
            return $m[1] . e($api) . $m[3];
        },
        $html
    );
    return $html;
}

function km_music_player_html_strip($html)
{
    $html = (string) $html;
    // 去掉播放器宿主标签（成对或自闭合）。
    $html = preg_replace('/<yxs-music-player\b[^>]*>.*?<\/yxs-music-player>/is', '', $html);
    $html = preg_replace('/<yxs-music-player\b[^>]*\/>/is', '', $html);
    // 去掉播放器脚本，避免脚本自己再创建一个空宿主。
    $html = preg_replace('/<script\b[^>]*\bsrc\s*=\s*["\'][^"\']*music-player(?:\.min)?\.js[^"\']*["\'][^>]*>\s*<\/script>/is', '', $html);
    return trim($html);
}

function render_footer()
{
    $me = current_user();
    $themeLibrary = site_theme_library();
    $deviceMode = device_view_mode();
    $pageName = $GLOBALS['PAGE'] ?? 'home';
    $extUnread = $me ? (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('messages') . ' WHERE to_id = ? AND is_read = 0', [$me['id']], 0) : 0;
    ?>
</main>

<footer class="site-footer">
  <div class="footer-inner">
    <div class="footer-snow">
      <svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="1.6" width="26" height="26"><g stroke-linecap="round"><path d="M32 6v52M10 19l44 26M54 19L10 45"/><path d="M32 14l-5 5M32 14l5 5M32 50l-5-5M32 50l5-5"/><circle cx="32" cy="32" r="5"/></g></svg>
    </div>
    <p><?= e(setting('footer_text', '© 木漏茶室')) ?></p>
    <p class="footer-meta"><?= e(setting('site_name', '木漏茶室')) ?> · Powered by 木漏茶室论坛 v<?= APP_VERSION ?> · PHP <?= PHP_VERSION ?></p>
    <?php if ($pageName === 'home'): ?>
    <p class="footer-blackroom"><a href="<?= e(page_url('blackroom')) ?>">小黑屋</a><span>查看处罚记录与释放页</span></p>
    <?php endif; ?>
    <div class="device-switch" role="group" aria-label="<?= e(t('browse_mode', '浏览模式')) ?>">
      <span class="device-switch-label"><?= e(t('browse_mode', '浏览模式')) ?></span>
      <div class="device-switch-btns">
        <?php foreach (['mobile' => t('device_mobile', '手机端'), 'desktop' => t('device_desktop', '电脑端'), 'tablet' => t('device_tablet', '平板端')] as $modeKey => $modeLabel): ?>
        <a class="device-switch-btn<?= $deviceMode === $modeKey ? ' on' : '' ?>" href="<?= e(device_view_url($modeKey)) ?>"<?= $deviceMode === $modeKey ? ' aria-current="true"' : '' ?>><?= e($modeLabel) ?></a>
        <?php endforeach; ?>
      </div>
      <span class="device-switch-note"><?= e(t('device_note', '首次访问自动识别当前设备')) ?></span>
    </div>
    <?php if ($pageName === 'home'): ?>
    <div class="lang-switch" role="group" aria-label="<?= e(t('language', '语言')) ?>">
      <span class="lang-switch-label"><?= e(t('language', '语言')) ?></span>
      <form method="post" action="<?= e(page_url('home')) ?>" class="lang-switch-form">
        <?= csrf_field() ?>
        <input type="hidden" name="act" value="set_lang">
        <select name="lang" onchange="this.form.submit()" aria-label="<?= e(t('language', '语言')) ?>">
          <?php foreach (km_languages() as $langKey => $langLabel): ?>
            <option value="<?= e($langKey) ?>" <?= km_lang() === $langKey ? 'selected' : '' ?>><?= e($langLabel) ?></option>
          <?php endforeach; ?>
        </select>
      </form>
      <span class="lang-switch-note"><?= e(t('language_note', '仅保存到当前浏览器')) ?></span>
    </div>
    <?php endif; ?>
  </div>
  <?php
    $homeFooterHtml = km_music_player_html_normalize(trim((string) setting('home_footer_html', '')));
    $globalHtmlForDedupe = trim((string) setting('site_global_html', ''));
    // 全站 HTML 已经有播放器时，首页底部不再重复输出同一播放器；否则第二个宿主会被组件忽略，首页看起来“没有播放器”。
    if ($homeFooterHtml !== '' && km_music_player_html_detect($globalHtmlForDedupe) && km_music_player_html_detect($homeFooterHtml)) {
        $homeFooterHtml = km_music_player_html_strip($homeFooterHtml);
    }
  ?>
  <?php if ($homeFooterHtml !== '' && $pageName === 'home'): ?>
  <div class="home-footer-html"><?= $homeFooterHtml ?></div>
  <?php endif; ?>
  <?= plugin_hook('layout_footer') ?>
</footer>

<nav class="bottom-nav">
  <a class="<?= $pageName === 'home' ? 'on' : '' ?>" href="<?= e(page_url('home')) ?>">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M4 11l8-7 8 7v9H4z"/></svg><span><?= e(t('home', '首页')) ?></span>
  </a>
  <a class="<?= $pageName === 'compose' ? 'on' : '' ?>" href="<?= e(page_url('compose')) ?>">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 5v14M5 12h14"/></svg><span><?= e(t('compose', '发帖')) ?></span>
  </a>
  <a class="<?= $pageName === 'extensions' ? 'on' : '' ?>" href="<?= e(page_url('extensions')) ?>">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="4" y="4" width="7" height="7" rx="1.6"/><rect x="13" y="4" width="7" height="7" rx="1.6"/><rect x="4" y="13" width="7" height="7" rx="1.6"/><rect x="13" y="13" width="7" height="7" rx="1.6"/></svg><span><?= e(t('extensions', '扩展')) ?></span>
    <?php if ($extUnread): ?><i class="badge"><?= $extUnread > 99 ? '99+' : $extUnread ?></i><?php endif; ?>
  </a>
  <a class="<?= in_array($pageName, ['profile', 'notifications'], true) ? 'on' : '' ?>" href="<?= e(page_url($me ? 'profile' : 'login')) ?>">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="12" cy="8" r="3.6"/><path d="M5 20c1.2-3.4 3.8-5 7-5s5.8 1.6 7 5"/></svg><span><?= e(t('profile', '我的')) ?></span>
  </a>
  <?php if (is_admin(current_user())): ?>
  <a class="<?= $pageName === 'admin' ? 'on' : '' ?>" href="<?= e(page_url('admin')) ?>">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M4 6h16M4 12h16M4 18h10"/></svg><span><?= e(t('admin', '后台')) ?></span>
  </a>
  <?php endif; ?>
</nav>

<?php
$entryNotice = null;
$entryUser = current_user();
if (!in_array($pageName, ['admin', 'login', 'register', 'announcements', 'announcement', 'official_notify', 'plugin_mall'], true)) {
    $entryNotice = announcement_latest_active('modal');
}
if ($entryNotice && ((int) ($entryNotice['show_every_refresh'] ?? 0) === 1 || (int) ($entryNotice['show_every_visit'] ?? 0) === 1)
    && $pageName !== 'home') {
    // 「每次进入本站」弹窗只在首页/站点入口出现，避免挡住通知、好友等操作页
    $entryNotice = null;
}
if ($entryNotice && $entryUser && (int) ($entryNotice['show_limit'] ?? 0) > 0
    && announcement_view_count((int) $entryNotice['id'], (int) $entryUser['id']) >= (int) $entryNotice['show_limit']) {
    $entryNotice = null;
}
if ($entryNotice):
$entryAuthor = announcement_author($entryNotice);
?>
<section class="modal announcement-entry-modal" id="entryAnnouncementModal" hidden
  data-notice-id="<?= (int) $entryNotice['id'] ?>"
  data-skip-key="km_notice_skip_<?= (int) $entryNotice['id'] ?>_<?= date('Y-m-d') ?>"
  data-close-key="km_notice_close_<?= (int) $entryNotice['id'] ?>"
  data-every-visit="<?= (int) ($entryNotice['show_every_visit'] ?? 0) ?>"
  data-every-refresh="<?= (int) ($entryNotice['show_every_refresh'] ?? 0) ?>"
  data-allow-snooze="<?= (int) ($entryNotice['allow_snooze'] ?? 0) ?>"
  data-snooze-key="km_notice_snooze_<?= (int) $entryNotice['id'] ?>"
  data-limit="<?= (int) ($entryNotice['show_limit'] ?? 0) ?>"
  data-logged-in="<?= $entryUser ? '1' : '0' ?>"
  data-api-url="<?= e(BASE_PATH . '/api.php') ?>"
  data-token="<?= e(csrf_token()) ?>">
  <div class="modal-mask" data-entry-notice-close></div>
  <div class="modal-card announcement-entry-card">
    <div class="announcement-entry-head">
      <span class="announcement-kind-pill"><?= e(announcement_kind_label($entryNotice['kind'])) ?></span>
      <button class="readers-close" type="button" data-entry-notice-close aria-label="关闭公告">×</button>
    </div>
    <?php if ($entryAuthor): ?>
    <div class="announcement-entry-author">
      <a class="notice-author" href="<?= e(page_url('user', ['id' => (int) $entryAuthor['id']])) ?>">
        <span class="announcement-entry-avatar">
          <?= avatar_html($entryAuthor, 'notice-avatar') ?>
          <?php if ((int) $entryAuthor['verified'] === 1): ?><span class="avatar-v v-<?= verify_style_of($entryAuthor) ?>">V</span><?php endif; ?>
        </span>
        <span><strong><?= e(display_name($entryAuthor)) ?></strong><?= verify_badge($entryAuthor, true) ?></span>
      </a>
      <span class="muted"><?= is_official_account($entryAuthor) ? '官方公告' : '公告' ?></span>
    </div>
    <?php endif; ?>
    <h2><?= e($entryNotice['title']) ?></h2>
    <article class="announcement-body"><?= announcement_content_html($entryNotice) ?></article>
    <div class="announcement-entry-actions">
      <a class="btn-mini ghost" href="<?= e(page_url('announcement', ['id' => (int) $entryNotice['id']])) ?>">查看详情</a>
      <button class="btn-mini ghost" type="button" data-entry-notice-today>今日不提示</button>
      <?php if ((int) ($entryNotice['allow_snooze'] ?? 0) === 1): ?>
      <button class="btn-mini ghost" type="button" data-entry-notice-snooze>12小时内不再提示</button>
      <?php endif; ?>
      <button class="btn-primary" type="button" data-entry-notice-close>关闭公告</button>
    </div>
  </div>
</section>
<script>
(function () {
  var modal = document.getElementById('entryAnnouncementModal');
  if (!modal) return;
  var everyVisit = modal.dataset.everyVisit === '1';
  var everyRefresh = modal.dataset.everyRefresh === '1';
  var allowSnooze = modal.dataset.allowSnooze === '1';
  var snoozeKey = modal.dataset.snoozeKey || '';
  if (allowSnooze && snoozeKey) {
    try {
      if (Number(localStorage.getItem(snoozeKey) || 0) > Date.now()) return;
    } catch (e) {}
  }
  var enteredKey = 'km_notice_entered_' + modal.dataset.noticeId;
  if (!everyRefresh) {
    if (everyVisit) {
      try { if (sessionStorage.getItem(enteredKey) === '1') return; } catch (e) {}
    } else {
      try {
        if (localStorage.getItem(modal.dataset.skipKey) === '1') return;
        if (sessionStorage.getItem(modal.dataset.closeKey) === '1') return;
      } catch (e) {}
    }
  }
  modal.hidden = false;
  document.body.classList.add('modal-open');
  if (everyVisit) {
    try { sessionStorage.setItem(enteredKey, '1'); } catch (e) {}
  }
  function recordView() {
    if (modal.dataset.loggedIn !== '1') return;
    var body = new FormData();
    body.append('action', 'announcement_view');
    body.append('announcement_id', modal.dataset.noticeId);
    body.append('_token', modal.dataset.token);
    fetch(modal.dataset.apiUrl, {
      method: 'POST',
      body: body,
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      credentials: 'same-origin'
    }).catch(function () {});
  }
  recordView();
  function closeNotice(remember) {
    modal.hidden = true;
    document.body.classList.remove('modal-open');
    if (remember) {
      try { sessionStorage.setItem(modal.dataset.closeKey, '1'); } catch (e) {}
    }
  }
  modal.querySelectorAll('[data-entry-notice-close]').forEach(function (btn) {
    btn.addEventListener('click', function () { closeNotice(true); });
  });
  var today = modal.querySelector('[data-entry-notice-today]');
  if (today) today.addEventListener('click', function () {
    try { localStorage.setItem(modal.dataset.skipKey, '1'); } catch (e) {}
    closeNotice(true);
  });
  var snooze = modal.querySelector('[data-entry-notice-snooze]');
  if (snooze) snooze.addEventListener('click', function () {
    try { localStorage.setItem(snoozeKey, String(Date.now() + 12 * 60 * 60 * 1000)); } catch (e) {}
    closeNotice(true);
  });
})();
</script>
<?php endif; ?>

<?php
require_once APP_ROOT . '/inc/security_guard.php';
?>


<div class="theme-panel" id="themePanel">
  <div class="tp-title">主题</div>
  <?php foreach ($themeLibrary as $themeItem): ?>
    <button data-mode="<?= e($themeItem['key']) ?>" type="button"><?= e($themeItem['name']) ?></button>
  <?php endforeach; ?>
</div>

<script>
window.KM_BASE = <?= json_encode(BASE_PATH, JSON_UNESCAPED_UNICODE) ?>;
window.KM_TOKEN = <?= json_encode(csrf_token()) ?>;
window.KM_UPLOAD_POST_MAX = <?= (int) upload_limit_bytes('upload_post_mb', 1000) ?>;
window.KM_UID = <?= (int) (current_user()['id'] ?? 0) ?>;
window.KM_IS_ADMIN = <?= is_admin(current_user()) ? 'true' : 'false' ?>;
window.KM_IS_SUPER = <?= is_superadmin(current_user()) ? 'true' : 'false' ?>;
window.KM_GUARD_ON = <?= function_exists('realtime_guard_enabled') && realtime_guard_enabled() ? 'true' : 'false' ?>;
window.KM_GUARD_REFRESH = <?= function_exists('realtime_guard_refresh_enabled') && realtime_guard_refresh_enabled() ? 'true' : 'false' ?>;
</script>

<div class="km-music-dock" id="kmMusicDock" hidden>
  <div class="km-md-mini" data-md-mini>
    <button type="button" class="km-md-thumb" data-md-expand aria-label="展开音乐播放器">
      <img data-md-cover alt="" hidden>
      <span class="km-md-note" aria-hidden="true">♪</span>
    </button>
    <button type="button" class="km-md-mini-info" data-md-expand>
      <strong data-md-title>—</strong>
      <small data-md-artist></small>
    </button>
    <button type="button" class="km-md-circle" data-md-play aria-label="播放"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg></button>
    <button type="button" class="km-md-circle km-md-chevron" data-md-expand aria-label="展开"><svg viewBox="0 0 24 24"><path d="M7 14l5-5 5 5"/></svg></button>
  </div>
  <div class="km-md-panel" data-md-panel hidden>
    <div class="km-md-head">
      <span class="km-md-grip" aria-hidden="true"></span>
      <div class="km-md-head-actions">
        <button type="button" class="km-md-circle km-md-collapse" data-md-collapse aria-label="收起"><svg viewBox="0 0 24 24"><path d="M7 10l5 5 5-5"/></svg></button>
      </div>
    </div>
    <div class="km-md-now">
      <span class="km-md-cover">
        <img data-md-cover-lg alt="" hidden>
        <span class="km-md-note" aria-hidden="true">♪</span>
      </span>
      <div class="km-md-meta">
        <strong data-md-title-lg>—</strong>
        <small data-md-artist-lg></small>
      </div>
    </div>
    <div class="km-md-line">
      <input type="range" min="0" max="1000" step="1" value="0" data-md-progress aria-label="播放进度">
      <div class="km-md-times"><span data-md-cur>0:00</span><span data-md-total>0:00</span></div>
    </div>
    <div class="km-md-tools">
      <button type="button" class="km-md-tool" data-md-prev aria-label="上一首"><svg viewBox="0 0 24 24"><path d="M6 5h2v14H6zM20 5v14L9 12z"/></svg></button>
      <button type="button" class="km-md-main" data-md-play aria-label="播放"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg></button>
      <button type="button" class="km-md-tool" data-md-next aria-label="下一首"><svg viewBox="0 0 24 24"><path d="M18 5h-2v14h2zM4 5v14L15 12z"/></svg></button>
      <a class="km-md-download-pill" data-md-download href="#" download hidden aria-label="下载当前文件"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v11m0 0l4-4m-4 4l-4-4M5 19h14"/></svg><span>下载</span></a>
      <button type="button" class="km-md-tool km-md-mute" data-md-mute aria-label="静音"><svg viewBox="0 0 24 24"><path class="v-on" d="M4 9v6h4l5 4V5L8 9zM16 8a5 5 0 010 8M18.5 5.5a9 9 0 010 13"/><path class="v-off" d="M4 9v6h4l5 4V5L8 9zM16 9l5 6M21 9l-5 6" style="display:none"/></svg></button>
      <div class="km-md-vol"><input type="range" min="0" max="100" step="1" value="100" data-md-volume aria-label="音量"></div>
    </div>
    <div class="km-md-bottom">
      <div class="km-md-lyric" data-md-lyric>暂无歌词</div>
      <div class="km-md-wave" data-md-wave aria-hidden="true"></div>
    </div>
  </div>
  <audio id="kmMusicAudio" preload="metadata"></audio>
</div>

<script src="<?= e(asset('js/login-history.js')) ?>"></script>
<script src="<?= e(asset('js/app.js')) ?>"></script>
<script src="<?= e(asset('js/music-dock.js')) ?>"></script>
<script src="<?= e(asset('js/spa-nav.js')) ?>"></script>
<script src="<?= e(asset('js/realtime-guard.js')) ?>"></script>
<?php $siteGlobalHtml = km_music_player_html_normalize(trim((string) setting('site_global_html', ''))); ?>
<?php if ($siteGlobalHtml !== ''): ?>
<?= $siteGlobalHtml ?>
<?php endif; ?>
</body>
</html>
<?php
}

/**
 * 空状态
 */
function empty_state($text, $sub = '')
{
    echo '<div class="empty"><div class="empty-snow">❄</div><p>' . e($text) . '</p>'
        . ($sub ? '<small>' . e($sub) . '</small>' : '') . '</div>';
}
