<?php
// Shared application colour-mode bootstrap. Keep this script before page styles so
// the saved mode is applied before the first paint (avoids a light-theme flash).
$assetsUrl = $assetsUrl ?? '';
?>
<script>
    (function () {
        var key = 'ppphp-color-theme';
        var choice = 'system';
        var allowed = ['system', 'light', 'midnight', 'dracula', 'gruvbox', 'rosepine'];
        try {
            var saved = window.localStorage.getItem(key);
            if (saved === 'dark') saved = 'midnight';
            if (saved === 'graphite') saved = 'dracula';
            if (saved === 'aurora') saved = 'gruvbox';
            if (allowed.indexOf(saved) !== -1) choice = saved;
        } catch (error) {}
        var systemDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        var theme = choice === 'system' ? (systemDark ? 'dark' : 'light') : (choice === 'light' ? 'light' : 'dark');
        document.documentElement.setAttribute('data-pp-theme-choice', choice);
        document.documentElement.setAttribute('data-pp-theme', theme);
        document.documentElement.setAttribute('data-bs-theme', theme);
        document.documentElement.style.colorScheme = theme;
    }());
</script>
<?php
// Cache-bust the theme assets by file mtime so an edit to app-theme.css / .js is
// picked up on the next load instead of being served stale from the browser cache
// (these are long-lived static files with no version in their path otherwise).
$__assetFsBase = null;
foreach ([constant('BASE_PATH') . '/public/assets', constant('BASE_PATH') . '/assets'] as $__cand) {
    if (is_dir($__cand)) { $__assetFsBase = $__cand; break; }
}
$__ver = static function (string $rel) use ($__assetFsBase): string {
    if ($__assetFsBase && is_file($__assetFsBase . '/' . $rel)) {
        return '?v=' . (string) (@filemtime($__assetFsBase . '/' . $rel) ?: '');
    }
    return '';
};
?>
<link href="<?= htmlspecialchars((string)$assetsUrl) ?>/css/app-theme.css<?= $__ver('css/app-theme.css') ?>" rel="stylesheet">
<script src="<?= htmlspecialchars((string)$assetsUrl) ?>/js/app-theme.js<?= $__ver('js/app-theme.js') ?>" defer></script>
<?php
// Visitor-analytics beacon. Sends the device/engagement detail only the browser
// knows (timezone, screen, connection, active time) to /pp/visit so the Visitors
// console shows accurate data. Guarded so client bundles — which carry no
// analytics code — skip it entirely. Loads once, deferred, never blocking.
if (class_exists(\PpPhp\Core\Analytics\VisitorLog::class)):
    $ppVisitUrl = preg_replace('#/assets/?$#', '', (string) ($assetsUrl ?? '')) . '/pp/visit';
?>
<script>window.__PP_VISIT=<?= json_encode($ppVisitUrl, JSON_UNESCAPED_SLASHES) ?>;</script>
<script src="<?= htmlspecialchars((string) ($assetsUrl ?? '')) ?>/js/pp-visit.js" defer></script>
<?php endif; ?>
