// Keyboard Shortcuts — global "?" opens a modal documenting every
// keyboard affordance in the app. Discoverability for power users
// without cluttering the UI for everyone else.

(function () {
  const e = React.createElement;
  const { useState, useEffect } = React;

  const SHORTCUTS = [
    {
      group: 'Global',
      items: [
        { keys: ['⌘', 'J'], label: 'Open / close AI assistant' },
        { keys: ['⌘', 'K'], label: 'Search the catalog' },
        { keys: ['?'],      label: 'Show this shortcut list' },
        { keys: ['Esc'],    label: 'Close any open modal or popover' },
      ],
    },
    {
      group: 'AI chat',
      items: [
        { keys: ['Enter'],         label: 'Send message' },
        { keys: ['Shift', 'Enter'], label: 'New line in the prompt' },
        { keys: ['Esc'],           label: 'Close the sidebar' },
      ],
    },
    {
      group: 'List detail',
      items: [
        { keys: ['Alt', '↑/↓'], label: 'Reorder selected item up or down' },
        { keys: ['Enter'],      label: 'Open the focused item' },
        { keys: ['Tab'],        label: 'Move focus through items' },
      ],
    },
  ];

  function KeyboardShortcutsHelp() {
    const [open, setOpen] = useState(false);

    useEffect(() => {
      const onKey = (ev) => {
        // Open on ? — but ONLY when no input is focused (otherwise the
        // user is typing a question mark, not asking for help).
        const tag = (document.activeElement && document.activeElement.tagName) || '';
        const isTyping = tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT'
          || (document.activeElement && document.activeElement.isContentEditable);
        if (ev.key === '?' && !isTyping && !ev.metaKey && !ev.ctrlKey) {
          ev.preventDefault();
          setOpen(o => !o);
        } else if (ev.key === 'Escape' && open) {
          setOpen(false);
        }
      };
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
    }, [open]);

    if (!open) return null;
    return e(React.Fragment, null,
      e('div', { className: 'ksh-scrim', onClick: () => setOpen(false) }),
      e('div', { className: 'ksh-modal', role: 'dialog', 'aria-label': 'Keyboard shortcuts' },
        e('header', { className: 'ksh-head' },
          e('h2', null, 'Keyboard shortcuts'),
          e('button', { type: 'button', className: 'ksh-close', onClick: () => setOpen(false), 'aria-label': 'Close' },
            e('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round' },
              e('path', { d: 'M6 6 L18 18 M18 6 L6 18' })
            )
          )
        ),
        e('div', { className: 'ksh-body' },
          SHORTCUTS.map((g, gi) =>
            e('section', { key: gi, className: 'ksh-section' },
              e('h3', null, g.group),
              e('ul', null,
                g.items.map((it, ii) =>
                  e('li', { key: ii },
                    e('span', { className: 'ksh-keys' },
                      it.keys.map((k, ki) =>
                        e(React.Fragment, { key: ki },
                          e('kbd', null, k),
                          ki < it.keys.length - 1 && e('span', { className: 'ksh-plus' }, '+')
                        )
                      )
                    ),
                    e('span', { className: 'ksh-label' }, it.label)
                  )
                )
              )
            )
          )
        ),
        e('footer', { className: 'ksh-foot' },
          e('span', null, 'Press '), e('kbd', null, '?'), e('span', null, ' anytime to bring this back.')
        )
      )
    );
  }

  window.KeyboardShortcutsHelp = KeyboardShortcutsHelp;
})();
