<?php
/**
 * Global keyboard-shortcuts layer for the PPphp console.
 *
 * A GitHub/Linear-style "g then key" navigation plus a discoverable cheatsheet.
 * Self-contained (overlay + styles + script). Drop it into any signed-in navbar;
 * reads $baseUrl and $project['slug'] (when inside a project workspace).
 *
 *   ?            open this shortcuts cheatsheet
 *   /            open the ⌘K command palette
 *   g <key>      jump — context-aware (console destinations, or this project's
 *                pages when inside a project). Keys come from ProjectNav so they
 *                always match the sidebar.
 *
 * Never fires while typing in a field or when a modal / palette / dialog is open.
 */
$__ksBase = rtrim((string) ($baseUrl ?? ''), '/');
$__ksSlug = (string) ($project['slug'] ?? '');

// The active "g" map (label + app-relative path), context-aware.
if ($__ksSlug !== '') {
    $__go = [];
    $__ksStandalone = \PpPhp\Core\ProjectDatabaseProfile::isStandaloneSlug($__ksSlug);
    foreach (\PpPhp\Core\ProjectNav::items('', $__ksStandalone) as $it) {
        $__go[strtolower((string) $it['key'])] = [(string) $it['label'], '/project/' . rawurlencode($__ksSlug) . (string) $it['uri']];
    }
    $__ctxLabel = 'This project';
} else {
    $__go = [
        'd' => ['Dashboard', '/'],
        'p' => ['Projects', '/projects'],
        's' => ['Settings', '/settings/core-config'],
        'v' => ['Virtual Databases', '/database-manager'],
        'u' => ['Data Studio', '/database-manager/studio'],
        'm' => ['Plugin Manager', '/plugin-manager'],
    ];
    $__ctxLabel = 'Go to';
}
// Universal jumps present in every context.
$__go['x'] = ['Projects', '/projects'];
if (!isset($__go['h'])) { $__go['h'] = ['Help', '/help']; }
ksort($__go);
?>
<div class="pp-kbd" id="ppKbd"
     data-base="<?= htmlspecialchars($__ksBase) ?>"
     data-go="<?= htmlspecialchars(json_encode($__go, JSON_UNESCAPED_SLASHES), ENT_QUOTES) ?>"
     data-ctx="<?= htmlspecialchars($__ctxLabel) ?>" hidden>
    <div class="pp-kbd-backdrop" data-pp-kbd-close></div>
    <div class="pp-kbd-panel" role="dialog" aria-modal="true" aria-label="Keyboard shortcuts">
        <div class="pp-kbd-head">
            <strong><i class="bi bi-keyboard"></i> Keyboard shortcuts</strong>
            <button type="button" class="pp-kbd-x" data-pp-kbd-close aria-label="Close">&times;</button>
        </div>
        <div class="pp-kbd-body">
            <div class="pp-kbd-col">
                <div class="pp-kbd-grouphd">Global</div>
                <div class="pp-kbd-row"><span>Command palette</span><span class="pp-kbd-keys"><kbd>⌘</kbd><kbd>K</kbd> <em>or</em> <kbd>/</kbd></span></div>
                <div class="pp-kbd-row"><span>This cheatsheet</span><span class="pp-kbd-keys"><kbd>?</kbd></span></div>
                <div class="pp-kbd-row"><span>Close / cancel</span><span class="pp-kbd-keys"><kbd>Esc</kbd></span></div>
            </div>
            <div class="pp-kbd-col" id="ppKbdGo">
                <div class="pp-kbd-grouphd"><?= htmlspecialchars($__ctxLabel) ?> <span class="pp-kbd-prefix">press <kbd>g</kbd> then…</span></div>
                <?php foreach ($__go as $k => $dest): ?>
                <div class="pp-kbd-row"><span><?= htmlspecialchars($dest[0]) ?></span><span class="pp-kbd-keys"><kbd>g</kbd><kbd><?= htmlspecialchars($k) ?></kbd></span></div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="pp-kbd-foot">Tip: shortcuts pause while you're typing or a dialog is open.</div>
    </div>
</div>
<div class="pp-kbd-hint" id="ppKbdHint" hidden><kbd>g</kbd> <span>go to… <em>(? for list)</em></span></div>

<style>
    .pp-kbd { position: fixed; inset: 0; z-index: 3100; display: flex; align-items: flex-start; justify-content: center; }
    .pp-kbd[hidden], .pp-kbd-hint[hidden] { display: none; }
    .pp-kbd-backdrop { position: absolute; inset: 0; background: rgba(2, 6, 23, .55); backdrop-filter: blur(2px); }
    .pp-kbd-panel { position: relative; margin-top: 8vh; width: min(680px, calc(100vw - 24px)); max-height: 84vh; overflow: hidden;
        display: flex; flex-direction: column; border-radius: 16px; background: var(--pp-surface, #fff); color: var(--pp-text, #1e293b);
        border: 1px solid var(--pp-border, #e2e8f0); box-shadow: 0 32px 90px rgba(2, 6, 23, .42); animation: pp-kbd-in .16s ease-out; }
    @keyframes pp-kbd-in { from { opacity: 0; transform: translateY(-8px) scale(.985); } to { opacity: 1; transform: none; } }
    @media (prefers-reduced-motion: reduce) { .pp-kbd-panel { animation: none; } }
    .pp-kbd-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; border-bottom: 1px solid var(--pp-border, #eef1f6); }
    .pp-kbd-head strong { font-size: 14px; display: inline-flex; align-items: center; gap: 8px; }
    .pp-kbd-x { border: 0; background: transparent; color: var(--pp-text-muted, #94a3b8); font-size: 22px; line-height: 1; cursor: pointer; }
    .pp-kbd-x:hover { color: var(--pp-text); }
    .pp-kbd-body { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 26px; padding: 14px 18px; overflow-y: auto; flex: 1 1 auto; min-height: 0; align-content: start; }
    @media (max-width: 619.98px) { .pp-kbd-body { grid-template-columns: 1fr; } }
    .pp-kbd-grouphd { font-size: 10.5px; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; color: var(--pp-text-muted, #94a3b8);
        padding: 6px 2px 8px; display: flex; align-items: baseline; gap: 8px; }
    .pp-kbd-prefix { text-transform: none; letter-spacing: 0; font-weight: 600; opacity: .8; }
    .pp-kbd-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 6px 2px; font-size: 13.5px; }
    .pp-kbd-row + .pp-kbd-grouphd { margin-top: 8px; }
    .pp-kbd-keys { display: inline-flex; align-items: center; gap: 4px; color: var(--pp-text-muted, #64748b); }
    .pp-kbd-keys em { font-style: normal; opacity: .7; padding: 0 2px; }
    .pp-kbd kbd, .pp-kbd-hint kbd { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 22px; padding: 0 6px;
        border-radius: 6px; background: var(--pp-surface-muted, #f1f5f9); border: 1px solid var(--pp-border, #e2e8f0);
        font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--pp-text, #334155); }
    .pp-kbd-foot { padding: 11px 18px; border-top: 1px solid var(--pp-border, #eef1f6); background: var(--pp-surface-muted, #f8fafc);
        font-size: 12px; color: var(--pp-text-muted, #64748b); }

    /* "g" go-mode hint chip, bottom-center. */
    .pp-kbd-hint { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); z-index: 3200;
        display: inline-flex; align-items: center; gap: 9px; padding: 9px 15px; border-radius: 11px; font-size: 13px; font-weight: 600;
        color: var(--pp-text, #1e293b); background: var(--pp-surface, #fff); border: 1px solid var(--pp-border, #e2e8f0);
        box-shadow: 0 16px 40px rgba(2, 6, 23, .3); animation: pp-kbd-in .12s ease-out; }
    .pp-kbd-hint em { font-style: normal; color: var(--pp-text-muted, #94a3b8); }
</style>

<script>
(function () {
    if (window.__ppKbdInit) return;
    window.__ppKbdInit = true;

    var root = document.getElementById('ppKbd');
    if (!root) return;
    var base = root.dataset.base || '';
    var GO = {};
    try { GO = JSON.parse(root.dataset.go || '{}'); } catch (e) { GO = {}; }
    var hint = document.getElementById('ppKbdHint');
    var sheetOpen = false, goMode = false, goTimer = null;

    function typing() {
        var a = document.activeElement;
        if (a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.tagName === 'SELECT' || a.isContentEditable)) return true;
        var pal = document.getElementById('ppCmdk'); if (pal && !pal.hidden) return true;   // palette open
        if (document.querySelector('.modal.show')) return true;                              // bootstrap modal
        if (document.querySelector('.swal2-container')) return true;                         // SweetAlert
        if (document.querySelector('#ppTour:not([hidden])')) return true;                    // welcome tour
        return false;
    }

    function openSheet() { root.hidden = false; sheetOpen = true; document.body.style.overflow = 'hidden'; }
    function closeSheet() { root.hidden = true; sheetOpen = false; document.body.style.overflow = ''; }
    function toggleSheet() { sheetOpen ? closeSheet() : openSheet(); }

    function enterGo() {
        goMode = true; hint.hidden = false;
        clearTimeout(goTimer);
        goTimer = setTimeout(clearGo, 1600);
    }
    function clearGo() { goMode = false; hint.hidden = true; clearTimeout(goTimer); }

    document.addEventListener('keydown', function (e) {
        if (e.metaKey || e.ctrlKey || e.altKey) return; // leave ⌘K and OS combos alone

        if (sheetOpen) { if (e.key === 'Escape' || e.key === '?') { e.preventDefault(); closeSheet(); } return; }

        if (e.key === '?' && !typing()) { e.preventDefault(); openSheet(); return; }

        if (goMode) {
            e.preventDefault();
            var k = (e.key || '').toLowerCase();
            clearGo();
            if (k === 'escape') return;
            var dest = GO[k];
            if (dest) { window.location.href = base + dest[1]; }
            else { hint.querySelector('span').innerHTML = 'no shortcut for <kbd>g</kbd> ' + (k.length === 1 ? k : ''); hint.hidden = false; setTimeout(function () { hint.hidden = true; }, 900); }
            return;
        }

        if (typing()) return;
        if (e.key === 'g') { e.preventDefault(); enterGo(); return; }
        if (e.key === '/') { e.preventDefault(); if (window.ppOpenPalette) window.ppOpenPalette(); return; }
    });

    root.querySelectorAll('[data-pp-kbd-close]').forEach(function (b) { b.addEventListener('click', closeSheet); });
    window.ppShowShortcuts = openSheet; // let the palette / a menu trigger it
}());
</script>
