/**
 * Early injection script for KeyPilot - runs at document_start
 * Makes SVG cursor available immediately before page load
 */

(function() {
  'use strict';

  // Constants extracted from main extension for early injection
  const CURSOR_ID = 'kpv2-cursor';
  const STYLE_ID = 'kpv2-early-style';
  const FOCUS_GREEN_BRIGHT = 'rgba(0,128,0,0.95)';
  const KEYBOARD_HELP_STORAGE_KEY = 'keypilot_keyboard_help_visible';
  const ONBOARDING_ACTIVE_STORAGE_KEY = 'keypilot_onboarding_active';
  const ONBOARDING_PROGRESS_STORAGE_KEY = 'keypilot_onboarding_progress';
  const SETTINGS_STORAGE_KEY = 'kp_settings_v1';
  // Keep in sync with Z_INDEX in src/config/constants.js
  const Z_CONTROL_STRIP = 2147483025;
  const Z_ONBOARDING_PANEL = 2147483026;
  const CONTROL_STRIP_DEFAULT_TOP_PX = 16;
  const CONTROL_STRIP_DEFAULT_LEFT_PX = 16;
  const CONTROL_STRIP_HEIGHT_PX = 28;
  const CONTROL_STRIP_ONBOARDING_GAP_PX = 8;
  const CURSOR_MODE = {
    NO_CUSTOM_CURSORS: 'NO-CUSTOM-CURSORS',
    CUSTOM_CURSORS: 'CUSTOM-CURSORS'
  };
  // Mirror the main extension's cursor mechanism so handoff is seamless.
  // See: `extension/src/modules/cursor.js` + `extension/src/modules/style-manager.js`
  const CURSOR_VAR = '--kpv2-cursor';
  const CURSOR_HIDDEN_CLASS = 'kpv2-cursor-hidden';
  // KP_EARLY_INJECT_UI_START
  // NOTE: This block is auto-generated by `extension/build.js` from:
  // - `extension/src/config/constants.js` (KEYBINDINGS, Z_INDEX)
  // - `extension/src/config/keyboard-layouts.js` (built-in layout data)
  // - `extension/src/ui/keybindings-ui-shared.js` (CSS + layout + style attr)
  // - `extension/pages/onboarding.xml` (early onboarding model)
  // - `extension/src/ui/onboarding-shared.js` (shell / progress / checklist DOM)
  // Do not edit by hand.
  const Z_FLOATING_KEYBOARD_HELP = 2147483045;
  const Z_KEYBINDINGS_POPOVER = 2147483046;
  const KEYBINDINGS_UI_STYLE_ATTR = "data-kp-keybindings-ui-style";
  const DEFAULT_KEYBOARD_LAYOUT_ID = "browsing-right";
  const KEYBOARD_LAYOUTS_BY_ID = {
  "browsing-right": [
    [
      {
        "type": "special",
        "text": "Tab",
        "className": "key key-tab"
      },
      {
        "type": "action",
        "id": "TAB_LEFT",
        "fallbackText": "Tab Left"
      },
      {
        "type": "action",
        "id": "TAB_RIGHT",
        "fallbackText": "Tab Right"
      },
      {
        "type": "action",
        "id": "PREVIEW_LINK_POPOVER",
        "fallbackText": "Preview Link"
      },
      {
        "type": "action",
        "id": "FORWARD",
        "fallbackText": "Go Forward"
      },
      {
        "type": "action",
        "id": "NEW_TAB",
        "fallbackText": "New Tab"
      },
      {
        "type": "action",
        "id": "RECTANGLE_HIGHLIGHT",
        "fallbackText": "Rectangle Select"
      },
      {
        "type": "key",
        "text": "U"
      },
      {
        "type": "action",
        "id": "COPY_HOVERED_IMAGE",
        "fallbackText": "Copy Image"
      },
      {
        "type": "key",
        "text": "O"
      },
      {
        "type": "action",
        "id": "OPEN_POPOVER",
        "fallbackText": "Open Popover"
      },
      {
        "type": "key",
        "text": "["
      },
      {
        "type": "key",
        "text": "]"
      },
      {
        "type": "action",
        "id": "DELETE",
        "fallbackText": "Delete Mode",
        "className": "key key-backspace"
      }
    ],
    [
      {
        "type": "special",
        "text": "Caps",
        "className": "key key-caps"
      },
      {
        "type": "action",
        "id": "CLOSE_TAB",
        "fallbackText": "Close Tab"
      },
      {
        "type": "action",
        "id": "BACK2",
        "fallbackText": "Go Back"
      },
      {
        "type": "action",
        "id": "BACK",
        "fallbackText": "Go Back"
      },
      {
        "type": "action",
        "id": "ACTIVATE",
        "fallbackText": "Click Element"
      },
      {
        "type": "action",
        "id": "ACTIVATE_NEW_TAB_BACKGROUND",
        "fallbackText": "Click New Tab Background"
      },
      {
        "type": "action",
        "id": "HIGHLIGHT",
        "fallbackText": "Text Select"
      },
      {
        "type": "action",
        "id": "TAB_HISTORY",
        "fallbackText": "History"
      },
      {
        "type": "action",
        "id": "TOGGLE_KEYBOARD_HELP",
        "fallbackText": "KB Reference"
      },
      {
        "type": "action",
        "id": "OMNIBOX",
        "fallbackText": "Omnibox"
      },
      {
        "type": "action",
        "id": "LAUNCHER",
        "fallbackText": "Launcher"
      },
      {
        "type": "action",
        "id": "OPEN_SETTINGS_POPOVER",
        "fallbackText": "Settings"
      },
      {
        "type": "special",
        "text": "Enter",
        "className": "key key-enter"
      }
    ],
    [
      {
        "type": "special",
        "text": "Shift",
        "className": "key key-shift"
      },
      {
        "type": "action",
        "id": "PAGE_TOP",
        "fallbackText": "Scroll To Top"
      },
      {
        "type": "action",
        "id": "PAGE_BOTTOM",
        "fallbackText": "Scroll To Bottom"
      },
      {
        "type": "action",
        "id": "PAGE_UP_INSTANT",
        "fallbackText": "Page Up Fast"
      },
      {
        "type": "action",
        "id": "PAGE_DOWN_INSTANT",
        "fallbackText": "Page Down Fast"
      },
      {
        "type": "action",
        "id": "ACTIVATE_NEW_TAB",
        "fallbackText": "Click New Tab"
      },
      {
        "type": "key",
        "text": "N"
      },
      {
        "type": "key",
        "text": "M"
      },
      {
        "type": "key",
        "text": ","
      },
      {
        "type": "action",
        "id": "COLS_TOGGLE",
        "fallbackText": "Cols Toggle"
      },
      {
        "type": "key",
        "text": "/"
      },
      {
        "type": "special",
        "text": "Shift",
        "className": "key key-shift"
      }
    ]
  ],
  "browsing-left": [
    [
      {
        "type": "special",
        "text": "Tab",
        "className": "key key-tab"
      },
      {
        "type": "key",
        "text": "Q"
      },
      {
        "type": "action",
        "id": "PREVIEW_LINK_POPOVER",
        "fallbackText": "Preview Link"
      },
      {
        "type": "action",
        "id": "COPY_HOVERED_IMAGE",
        "fallbackText": "Copy Image"
      },
      {
        "type": "action",
        "id": "RECTANGLE_HIGHLIGHT",
        "fallbackText": "Rectangle Select"
      },
      {
        "type": "key",
        "text": "T"
      },
      {
        "type": "action",
        "id": "NEW_TAB",
        "fallbackText": "New Tab"
      },
      {
        "type": "action",
        "id": "FORWARD",
        "fallbackText": "Go Forward"
      },
      {
        "type": "action",
        "id": "OPEN_POPOVER",
        "fallbackText": "Open Popover"
      },
      {
        "type": "action",
        "id": "TAB_RIGHT",
        "fallbackText": "Tab Right"
      },
      {
        "type": "action",
        "id": "TAB_LEFT",
        "fallbackText": "Tab Left"
      },
      {
        "type": "key",
        "text": "["
      },
      {
        "type": "key",
        "text": "]"
      },
      {
        "type": "action",
        "id": "DELETE",
        "fallbackText": "Delete Mode",
        "className": "key key-backspace"
      }
    ],
    [
      {
        "type": "special",
        "text": "Caps",
        "className": "key key-caps"
      },
      {
        "type": "action",
        "id": "LAUNCHER",
        "fallbackText": "Launcher"
      },
      {
        "type": "action",
        "id": "OMNIBOX",
        "fallbackText": "Omnibox"
      },
      {
        "type": "action",
        "id": "TOGGLE_KEYBOARD_HELP",
        "fallbackText": "KB Reference"
      },
      {
        "type": "action",
        "id": "TAB_HISTORY",
        "fallbackText": "History"
      },
      {
        "type": "action",
        "id": "HIGHLIGHT",
        "fallbackText": "Text Select"
      },
      {
        "type": "action",
        "id": "ACTIVATE_NEW_TAB_BACKGROUND",
        "fallbackText": "Click New Tab Background"
      },
      {
        "type": "action",
        "id": "ACTIVATE",
        "fallbackText": "Click Element"
      },
      {
        "type": "action",
        "id": "BACK",
        "fallbackText": "Go Back"
      },
      {
        "type": "action",
        "id": "BACK2",
        "fallbackText": "Go Back"
      },
      {
        "type": "action",
        "id": "CLOSE_TAB",
        "fallbackText": "Close Tab"
      },
      {
        "type": "action",
        "id": "OPEN_SETTINGS_POPOVER",
        "fallbackText": "Settings"
      },
      {
        "type": "special",
        "text": "Enter",
        "className": "key key-enter"
      }
    ],
    [
      {
        "type": "special",
        "text": "Shift",
        "className": "key key-shift"
      },
      {
        "type": "key",
        "text": "Z"
      },
      {
        "type": "key",
        "text": "X"
      },
      {
        "type": "key",
        "text": "C"
      },
      {
        "type": "key",
        "text": "V"
      },
      {
        "type": "action",
        "id": "PAGE_BOTTOM",
        "fallbackText": "Scroll To Bottom"
      },
      {
        "type": "action",
        "id": "ACTIVATE_NEW_TAB",
        "fallbackText": "Click New Tab"
      },
      {
        "type": "action",
        "id": "PAGE_DOWN_INSTANT",
        "fallbackText": "Page Down Fast"
      },
      {
        "type": "action",
        "id": "PAGE_UP_INSTANT",
        "fallbackText": "Page Up Fast"
      },
      {
        "type": "action",
        "id": "COLS_TOGGLE",
        "fallbackText": "Cols Toggle"
      },
      {
        "type": "action",
        "id": "PAGE_TOP",
        "fallbackText": "Scroll To Top"
      },
      {
        "type": "special",
        "text": "Shift",
        "className": "key key-shift"
      }
    ]
  ]
};
  const EARLY_KEYBINDINGS_BY_ID = {
  "browsing-right": {
    "TAB_LEFT": {
      "label": "Tab Left",
      "description": "Move To Previous Tab",
      "keyLabel": "Q",
      "displayKey": "Q",
      "keyboardClass": "key-gray"
    },
    "TAB_RIGHT": {
      "label": "Tab Right",
      "description": "Move To Next Tab",
      "keyLabel": "W",
      "displayKey": "W",
      "keyboardClass": "key-gray"
    },
    "PREVIEW_LINK_POPOVER": {
      "label": "Preview Link",
      "description": "Open Link Preview in Popover",
      "keyLabel": "E",
      "displayKey": "E",
      "keyboardClass": "key-preview-popover"
    },
    "FORWARD": {
      "label": "Go Forward",
      "description": "Go Forward (History)",
      "keyLabel": "R",
      "displayKey": "R",
      "keyboardClass": "key-forward"
    },
    "NEW_TAB": {
      "label": "New Tab",
      "description": "Open New Tab",
      "keyLabel": "T",
      "displayKey": "T",
      "keyboardClass": "key-gray"
    },
    "RECTANGLE_HIGHLIGHT": {
      "label": "Rectangle Select",
      "description": "Select text in a rectangle",
      "keyLabel": "Y",
      "displayKey": "Y",
      "keyboardClass": "key-rect-highlight"
    },
    "COPY_HOVERED_IMAGE": {
      "label": "Copy Image",
      "description": "Copy image under cursor to clipboard",
      "keyLabel": "I",
      "displayKey": "I",
      "keyboardClass": null
    },
    "OPEN_POPOVER": {
      "label": "Open Popover",
      "description": "Open Link in Popover",
      "keyLabel": "P",
      "displayKey": "P",
      "keyboardClass": "key-open-popover"
    },
    "DELETE": {
      "label": "Delete Mode",
      "description": "Delete Mode",
      "keyLabel": "Backspace",
      "displayKey": "Backspace",
      "keyboardClass": "key-delete"
    },
    "CLOSE_TAB": {
      "label": "Close Tab",
      "description": "Close Tab",
      "keyLabel": "A",
      "displayKey": "A",
      "keyboardClass": "key-close-tab"
    },
    "BACK2": {
      "label": "Go Back",
      "description": "Go Back (History)",
      "keyLabel": "S",
      "displayKey": "S",
      "keyboardClass": "key-back"
    },
    "BACK": {
      "label": "Go Back",
      "description": "Go Back (History)",
      "keyLabel": "D",
      "displayKey": "D",
      "keyboardClass": "key-back"
    },
    "ACTIVATE": {
      "label": "Click Element",
      "description": "Click Element",
      "keyLabel": "F",
      "displayKey": "F",
      "keyboardClass": "key-activate"
    },
    "ACTIVATE_NEW_TAB_BACKGROUND": {
      "label": "Click New Tab Background",
      "description": "Open Link in New Tab (Background, like middle click)",
      "keyLabel": "G",
      "displayKey": "G",
      "keyboardClass": "key-activate-new-over"
    },
    "HIGHLIGHT": {
      "label": "Text Select",
      "description": "Select text (character level)",
      "keyLabel": "H",
      "displayKey": "H",
      "keyboardClass": "key-highlight"
    },
    "TAB_HISTORY": {
      "label": "Tab History",
      "description": "Open Tab History (Branch-Retaining)",
      "keyLabel": "J",
      "displayKey": "J",
      "keyboardClass": "key-gray"
    },
    "TOGGLE_KEYBOARD_HELP": {
      "label": "KB Reference",
      "description": "Show/Hide the floating KeyPilot keyboard reference",
      "keyLabel": "K",
      "displayKey": "K",
      "keyboardClass": "key-purple"
    },
    "OMNIBOX": {
      "label": "Omnibox",
      "description": "Open Omnibox (Address Bar Overlay)",
      "keyLabel": "L",
      "displayKey": "L",
      "keyboardClass": "key-orange"
    },
    "LAUNCHER": {
      "label": "Launcher",
      "description": "Open Launcher (Quick Access to Sites)",
      "keyLabel": ";",
      "displayKey": ";",
      "keyboardClass": "key-launcher-orange"
    },
    "OPEN_SETTINGS_POPOVER": {
      "label": "Settings",
      "description": "Open KeyPilot Settings",
      "keyLabel": "'",
      "displayKey": "'",
      "keyboardClass": "key-settings-dark"
    },
    "PAGE_TOP": {
      "label": "Scroll To Top",
      "description": "Scroll to Top",
      "keyLabel": "Z",
      "displayKey": "Z",
      "keyboardClass": "key-scroll"
    },
    "PAGE_BOTTOM": {
      "label": "Scroll To Bottom",
      "description": "Scroll to Bottom",
      "keyLabel": "X",
      "displayKey": "X",
      "keyboardClass": "key-scroll"
    },
    "PAGE_UP_INSTANT": {
      "label": "Page Up Fast",
      "description": "Page Up (Instant)",
      "keyLabel": "C",
      "displayKey": "C",
      "keyboardClass": "key-scroll"
    },
    "PAGE_DOWN_INSTANT": {
      "label": "Page Down Fast",
      "description": "Page Down (Instant)",
      "keyLabel": "V",
      "displayKey": "V",
      "keyboardClass": "key-scroll"
    },
    "ACTIVATE_NEW_TAB": {
      "label": "Click New Tab",
      "description": "Open Link in New Tab (Foreground)",
      "keyLabel": "B",
      "displayKey": "B",
      "keyboardClass": "key-activate-new"
    },
    "COLS_TOGGLE": {
      "label": "Cols Toggle",
      "description": "Columnize element under cursor (multi-column layout)",
      "keyLabel": ".",
      "displayKey": ".",
      "keyboardClass": "key-cols"
    }
  },
  "browsing-left": {
    "TAB_LEFT": {
      "label": "Tab Left",
      "description": "Move To Previous Tab",
      "keyLabel": "P",
      "displayKey": "P",
      "keyboardClass": "key-gray"
    },
    "TAB_RIGHT": {
      "label": "Tab Right",
      "description": "Move To Next Tab",
      "keyLabel": "O",
      "displayKey": "O",
      "keyboardClass": "key-gray"
    },
    "PREVIEW_LINK_POPOVER": {
      "label": "Preview Link",
      "description": "Open Link Preview in Popover",
      "keyLabel": "W",
      "displayKey": "W",
      "keyboardClass": "key-preview-popover"
    },
    "FORWARD": {
      "label": "Go Forward",
      "description": "Go Forward (History)",
      "keyLabel": "U",
      "displayKey": "U",
      "keyboardClass": "key-forward"
    },
    "NEW_TAB": {
      "label": "New Tab",
      "description": "Open New Tab",
      "keyLabel": "Y",
      "displayKey": "Y",
      "keyboardClass": "key-gray"
    },
    "RECTANGLE_HIGHLIGHT": {
      "label": "Rectangle Select",
      "description": "Select text in a rectangle",
      "keyLabel": "R",
      "displayKey": "R",
      "keyboardClass": "key-rect-highlight"
    },
    "COPY_HOVERED_IMAGE": {
      "label": "Copy Image",
      "description": "Copy image under cursor to clipboard",
      "keyLabel": "E",
      "displayKey": "E",
      "keyboardClass": null
    },
    "OPEN_POPOVER": {
      "label": "Open Popover",
      "description": "Open Link in Popover",
      "keyLabel": "I",
      "displayKey": "I",
      "keyboardClass": "key-open-popover"
    },
    "DELETE": {
      "label": "Delete Mode",
      "description": "Delete Mode",
      "keyLabel": "Backspace",
      "displayKey": "Backspace",
      "keyboardClass": "key-delete"
    },
    "CLOSE_TAB": {
      "label": "Close Tab",
      "description": "Close Tab",
      "keyLabel": ";",
      "displayKey": ";",
      "keyboardClass": "key-close-tab"
    },
    "BACK2": {
      "label": "Go Back",
      "description": "Go Back (History)",
      "keyLabel": "L",
      "displayKey": "L",
      "keyboardClass": "key-back"
    },
    "BACK": {
      "label": "Go Back",
      "description": "Go Back (History)",
      "keyLabel": "K",
      "displayKey": "K",
      "keyboardClass": "key-back"
    },
    "ACTIVATE": {
      "label": "Click Element",
      "description": "Click Element",
      "keyLabel": "J",
      "displayKey": "J",
      "keyboardClass": "key-activate"
    },
    "ACTIVATE_NEW_TAB_BACKGROUND": {
      "label": "Click New Tab Background",
      "description": "Open Link in New Tab (Background, like middle click)",
      "keyLabel": "H",
      "displayKey": "H",
      "keyboardClass": "key-activate-new-over"
    },
    "HIGHLIGHT": {
      "label": "Text Select",
      "description": "Select text (character level)",
      "keyLabel": "G",
      "displayKey": "G",
      "keyboardClass": "key-highlight"
    },
    "TAB_HISTORY": {
      "label": "Tab History",
      "description": "Open Tab History (Branch-Retaining)",
      "keyLabel": "F",
      "displayKey": "F",
      "keyboardClass": "key-gray"
    },
    "TOGGLE_KEYBOARD_HELP": {
      "label": "KB Reference",
      "description": "Show/Hide the floating KeyPilot keyboard reference",
      "keyLabel": "D",
      "displayKey": "D",
      "keyboardClass": "key-purple"
    },
    "OMNIBOX": {
      "label": "Omnibox",
      "description": "Open Omnibox (Address Bar Overlay)",
      "keyLabel": "S",
      "displayKey": "S",
      "keyboardClass": "key-orange"
    },
    "LAUNCHER": {
      "label": "Launcher",
      "description": "Open Launcher (Quick Access to Sites)",
      "keyLabel": "a/`",
      "displayKey": "a/`",
      "keyboardClass": "key-launcher-orange"
    },
    "OPEN_SETTINGS_POPOVER": {
      "label": "Settings",
      "description": "Open KeyPilot Settings",
      "keyLabel": "'",
      "displayKey": "'",
      "keyboardClass": "key-settings-dark"
    },
    "PAGE_TOP": {
      "label": "Scroll To Top",
      "description": "Scroll to Top",
      "keyLabel": "/",
      "displayKey": "/",
      "keyboardClass": "key-scroll"
    },
    "PAGE_BOTTOM": {
      "label": "Scroll To Bottom",
      "description": "Scroll to Bottom",
      "keyLabel": "B",
      "displayKey": "B",
      "keyboardClass": "key-scroll"
    },
    "PAGE_UP_INSTANT": {
      "label": "Page Up Fast",
      "description": "Page Up (Instant)",
      "keyLabel": ",",
      "displayKey": ",",
      "keyboardClass": "key-scroll"
    },
    "PAGE_DOWN_INSTANT": {
      "label": "Page Down Fast",
      "description": "Page Down (Instant)",
      "keyLabel": "M",
      "displayKey": "M",
      "keyboardClass": "key-scroll"
    },
    "ACTIVATE_NEW_TAB": {
      "label": "Click New Tab",
      "description": "Open Link in New Tab (Foreground)",
      "keyLabel": "N",
      "displayKey": "N",
      "keyboardClass": "key-activate-new"
    },
    "COLS_TOGGLE": {
      "label": "Cols Toggle",
      "description": "Columnize element under cursor (multi-column layout)",
      "keyLabel": ".",
      "displayKey": ".",
      "keyboardClass": "key-cols"
    }
  }
};
  const KEYBINDINGS_KEYBOARD_LAYOUT = [
  [
    {
      "type": "special",
      "text": "Tab",
      "className": "key key-tab"
    },
    {
      "type": "action",
      "id": "TAB_LEFT",
      "fallbackText": "Tab Left"
    },
    {
      "type": "action",
      "id": "TAB_RIGHT",
      "fallbackText": "Tab Right"
    },
    {
      "type": "action",
      "id": "PREVIEW_LINK_POPOVER",
      "fallbackText": "Preview Link"
    },
    {
      "type": "action",
      "id": "FORWARD",
      "fallbackText": "Go Forward"
    },
    {
      "type": "action",
      "id": "NEW_TAB",
      "fallbackText": "New Tab"
    },
    {
      "type": "action",
      "id": "RECTANGLE_HIGHLIGHT",
      "fallbackText": "Rectangle Select"
    },
    {
      "type": "key",
      "text": "U"
    },
    {
      "type": "action",
      "id": "COPY_HOVERED_IMAGE",
      "fallbackText": "Copy Image"
    },
    {
      "type": "key",
      "text": "O"
    },
    {
      "type": "action",
      "id": "OPEN_POPOVER",
      "fallbackText": "Open Popover"
    },
    {
      "type": "key",
      "text": "["
    },
    {
      "type": "key",
      "text": "]"
    },
    {
      "type": "action",
      "id": "DELETE",
      "fallbackText": "Delete Mode",
      "className": "key key-backspace"
    }
  ],
  [
    {
      "type": "special",
      "text": "Caps",
      "className": "key key-caps"
    },
    {
      "type": "action",
      "id": "CLOSE_TAB",
      "fallbackText": "Close Tab"
    },
    {
      "type": "action",
      "id": "BACK2",
      "fallbackText": "Go Back"
    },
    {
      "type": "action",
      "id": "BACK",
      "fallbackText": "Go Back"
    },
    {
      "type": "action",
      "id": "ACTIVATE",
      "fallbackText": "Click Element"
    },
    {
      "type": "action",
      "id": "ACTIVATE_NEW_TAB_BACKGROUND",
      "fallbackText": "Click New Tab Background"
    },
    {
      "type": "action",
      "id": "HIGHLIGHT",
      "fallbackText": "Text Select"
    },
    {
      "type": "action",
      "id": "TAB_HISTORY",
      "fallbackText": "History"
    },
    {
      "type": "action",
      "id": "TOGGLE_KEYBOARD_HELP",
      "fallbackText": "KB Reference"
    },
    {
      "type": "action",
      "id": "OMNIBOX",
      "fallbackText": "Omnibox"
    },
    {
      "type": "action",
      "id": "LAUNCHER",
      "fallbackText": "Launcher"
    },
    {
      "type": "action",
      "id": "OPEN_SETTINGS_POPOVER",
      "fallbackText": "Settings"
    },
    {
      "type": "special",
      "text": "Enter",
      "className": "key key-enter"
    }
  ],
  [
    {
      "type": "special",
      "text": "Shift",
      "className": "key key-shift"
    },
    {
      "type": "action",
      "id": "PAGE_TOP",
      "fallbackText": "Scroll To Top"
    },
    {
      "type": "action",
      "id": "PAGE_BOTTOM",
      "fallbackText": "Scroll To Bottom"
    },
    {
      "type": "action",
      "id": "PAGE_UP_INSTANT",
      "fallbackText": "Page Up Fast"
    },
    {
      "type": "action",
      "id": "PAGE_DOWN_INSTANT",
      "fallbackText": "Page Down Fast"
    },
    {
      "type": "action",
      "id": "ACTIVATE_NEW_TAB",
      "fallbackText": "Click New Tab"
    },
    {
      "type": "key",
      "text": "N"
    },
    {
      "type": "key",
      "text": "M"
    },
    {
      "type": "key",
      "text": ","
    },
    {
      "type": "action",
      "id": "COLS_TOGGLE",
      "fallbackText": "Cols Toggle"
    },
    {
      "type": "key",
      "text": "/"
    },
    {
      "type": "special",
      "text": "Shift",
      "className": "key key-shift"
    }
  ]
];
  const EARLY_KEYBINDINGS = {
  "TAB_LEFT": {
    "label": "Tab Left",
    "description": "Move To Previous Tab",
    "keyLabel": "Q",
    "displayKey": "Q",
    "keyboardClass": "key-gray"
  },
  "TAB_RIGHT": {
    "label": "Tab Right",
    "description": "Move To Next Tab",
    "keyLabel": "W",
    "displayKey": "W",
    "keyboardClass": "key-gray"
  },
  "PREVIEW_LINK_POPOVER": {
    "label": "Preview Link",
    "description": "Open Link Preview in Popover",
    "keyLabel": "E",
    "displayKey": "E",
    "keyboardClass": "key-preview-popover"
  },
  "FORWARD": {
    "label": "Go Forward",
    "description": "Go Forward (History)",
    "keyLabel": "R",
    "displayKey": "R",
    "keyboardClass": "key-forward"
  },
  "NEW_TAB": {
    "label": "New Tab",
    "description": "Open New Tab",
    "keyLabel": "T",
    "displayKey": "T",
    "keyboardClass": "key-gray"
  },
  "RECTANGLE_HIGHLIGHT": {
    "label": "Rectangle Select",
    "description": "Select text in a rectangle",
    "keyLabel": "Y",
    "displayKey": "Y",
    "keyboardClass": "key-rect-highlight"
  },
  "COPY_HOVERED_IMAGE": {
    "label": "Copy Image",
    "description": "Copy image under cursor to clipboard",
    "keyLabel": "I",
    "displayKey": "I",
    "keyboardClass": null
  },
  "OPEN_POPOVER": {
    "label": "Open Popover",
    "description": "Open Link in Popover",
    "keyLabel": "P",
    "displayKey": "P",
    "keyboardClass": "key-open-popover"
  },
  "DELETE": {
    "label": "Delete Mode",
    "description": "Delete Mode",
    "keyLabel": "Backspace",
    "displayKey": "Backspace",
    "keyboardClass": "key-delete"
  },
  "CLOSE_TAB": {
    "label": "Close Tab",
    "description": "Close Tab",
    "keyLabel": "A",
    "displayKey": "A",
    "keyboardClass": "key-close-tab"
  },
  "BACK2": {
    "label": "Go Back",
    "description": "Go Back (History)",
    "keyLabel": "S",
    "displayKey": "S",
    "keyboardClass": "key-back"
  },
  "BACK": {
    "label": "Go Back",
    "description": "Go Back (History)",
    "keyLabel": "D",
    "displayKey": "D",
    "keyboardClass": "key-back"
  },
  "ACTIVATE": {
    "label": "Click Element",
    "description": "Click Element",
    "keyLabel": "F",
    "displayKey": "F",
    "keyboardClass": "key-activate"
  },
  "ACTIVATE_NEW_TAB_BACKGROUND": {
    "label": "Click New Tab Background",
    "description": "Open Link in New Tab (Background, like middle click)",
    "keyLabel": "G",
    "displayKey": "G",
    "keyboardClass": "key-activate-new-over"
  },
  "HIGHLIGHT": {
    "label": "Text Select",
    "description": "Select text (character level)",
    "keyLabel": "H",
    "displayKey": "H",
    "keyboardClass": "key-highlight"
  },
  "TAB_HISTORY": {
    "label": "Tab History",
    "description": "Open Tab History (Branch-Retaining)",
    "keyLabel": "J",
    "displayKey": "J",
    "keyboardClass": "key-gray"
  },
  "TOGGLE_KEYBOARD_HELP": {
    "label": "KB Reference",
    "description": "Show/Hide the floating KeyPilot keyboard reference",
    "keyLabel": "K",
    "displayKey": "K",
    "keyboardClass": "key-purple"
  },
  "OMNIBOX": {
    "label": "Omnibox",
    "description": "Open Omnibox (Address Bar Overlay)",
    "keyLabel": "L",
    "displayKey": "L",
    "keyboardClass": "key-orange"
  },
  "LAUNCHER": {
    "label": "Launcher",
    "description": "Open Launcher (Quick Access to Sites)",
    "keyLabel": ";",
    "displayKey": ";",
    "keyboardClass": "key-launcher-orange"
  },
  "OPEN_SETTINGS_POPOVER": {
    "label": "Settings",
    "description": "Open KeyPilot Settings",
    "keyLabel": "'",
    "displayKey": "'",
    "keyboardClass": "key-settings-dark"
  },
  "PAGE_TOP": {
    "label": "Scroll To Top",
    "description": "Scroll to Top",
    "keyLabel": "Z",
    "displayKey": "Z",
    "keyboardClass": "key-scroll"
  },
  "PAGE_BOTTOM": {
    "label": "Scroll To Bottom",
    "description": "Scroll to Bottom",
    "keyLabel": "X",
    "displayKey": "X",
    "keyboardClass": "key-scroll"
  },
  "PAGE_UP_INSTANT": {
    "label": "Page Up Fast",
    "description": "Page Up (Instant)",
    "keyLabel": "C",
    "displayKey": "C",
    "keyboardClass": "key-scroll"
  },
  "PAGE_DOWN_INSTANT": {
    "label": "Page Down Fast",
    "description": "Page Down (Instant)",
    "keyLabel": "V",
    "displayKey": "V",
    "keyboardClass": "key-scroll"
  },
  "ACTIVATE_NEW_TAB": {
    "label": "Click New Tab",
    "description": "Open Link in New Tab (Foreground)",
    "keyLabel": "B",
    "displayKey": "B",
    "keyboardClass": "key-activate-new"
  },
  "COLS_TOGGLE": {
    "label": "Cols Toggle",
    "description": "Columnize element under cursor (multi-column layout)",
    "keyLabel": ".",
    "displayKey": ".",
    "keyboardClass": "key-cols"
  }
};
  const EARLY_ONBOARDING_MODEL = {
  "slides": [
    {
      "id": "basic_navigation",
      "title": "Welcome to KeyPilot",
      "tasks": [
        {
          "id": "click_link",
          "label": "Hover over a link and press the `F` key to click it.",
          "when": {
            "type": "action",
            "action": "activate",
            "target": "link",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "go_back",
          "label": "To go back (history), press the `D` key.",
          "when": {
            "type": "action",
            "action": "back",
            "target": "",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "keyboard_key_info",
          "label": "Notice the Keyboard Reference window below. Hover over one of its keys to see what it does.",
          "when": {
            "type": "action",
            "action": "hover",
            "target": "keyboardHelpKey",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "toggle_extension_off",
          "label": "Notice the control strip above that says `ON`. Click it to turn KeyPilot completely off.",
          "when": {
            "type": "action",
            "action": "toggleExtension",
            "target": "",
            "mode": "",
            "change": "off"
          }
        }
      ],
      "onEnter": []
    },
    {
      "id": "text_box_mode",
      "title": "Text box mode",
      "tasks": [
        {
          "id": "enter_text_mode",
          "label": "Click a text field with F and it will receive typing.",
          "when": {
            "type": "mode",
            "action": "",
            "target": "",
            "mode": "text_focus",
            "change": "enter"
          }
        },
        {
          "id": "exit_text_mode",
          "label": "Press `Escape` to exit the text box.",
          "when": {
            "type": "mode",
            "action": "",
            "target": "",
            "mode": "text_focus",
            "change": "exit"
          }
        }
      ],
      "onEnter": []
    },
    {
      "id": "scrolling",
      "title": "Scrolling the page",
      "tasks": [
        {
          "id": "scroll_down",
          "label": "Scroll down with `V`.",
          "when": {
            "type": "action",
            "action": "scrollDown",
            "target": "",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "scroll_up",
          "label": "Scroll up with `C`.",
          "when": {
            "type": "action",
            "action": "scrollUp",
            "target": "",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "scroll_bottom",
          "label": "Go to the bottom of the page with `X`.",
          "when": {
            "type": "action",
            "action": "scrollBottom",
            "target": "",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "scroll_top",
          "label": "Go to the top of the page with `Z`.",
          "when": {
            "type": "action",
            "action": "scrollTop",
            "target": "",
            "mode": "",
            "change": ""
          }
        }
      ],
      "onEnter": []
    },
    {
      "id": "tabs",
      "title": "Tabs",
      "tasks": [
        {
          "id": "open_link_background_tab",
          "label": "Click a link into a new tab but don't open it (`G`).",
          "when": {
            "type": "action",
            "action": "activateNewTabBackground",
            "target": "link",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "open_link_new_tab",
          "label": "Click a link into a new tab (`B`).",
          "when": {
            "type": "action",
            "action": "activateNewTab",
            "target": "link",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "open_new_tab",
          "label": "Open a new tab (`T`).",
          "when": {
            "type": "action",
            "action": "newTab",
            "target": "",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "move_tabs",
          "label": "Move between tabs left (`Q`).",
          "when": {
            "type": "action",
            "action": "tabLeft",
            "target": "",
            "mode": "",
            "change": ""
          }
        },
        {
          "id": "move_tabs_2",
          "label": "Move between tabs right (`W`).",
          "when": {
            "type": "action",
            "action": "tabRight",
            "target": "",
            "mode": "",
            "change": ""
          }
        }
      ],
      "onEnter": []
    },
    {
      "id": "completion",
      "title": "Tutorial complete",
      "tasks": [],
      "onEnter": []
    }
  ]
};
  const POPUP_THEME_VARS = {
  "--fg": "#f8fafc",
  "--bg": "#0f172a",
  "--surface": "#1e293b",
  "--surface-light": "#334155",
  "--muted": "#94a3b8",
  "--ok": "#10b981",
  "--warn": "#f59e0b",
  "--err": "#44c7ef",
  "--brand": "#3b82f6",
  "--brand-dark": "#1e40af",
  "--border": "#334155",
  "--border2": "#4d617b"
};
  function applyPopupThemeVars(targetEl) {
    if (!targetEl || !targetEl.style) return;
    try {
      for (const [k, v] of Object.entries(POPUP_THEME_VARS)) {
        targetEl.style.setProperty(k, v);
      }
    } catch { /* ignore */ }
  }
  const KEYBINDINGS_UI_EARLY_CSS = `
/* KeyPilot Keybindings UI (injected) */
@font-face {
  font-family: "ROBOTECHGPRegular";
  src: url("__KP_FONT_ROBOTECH_URL__") format("truetype");
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

@font-face {
  font-family: "TitilliumText";
  src: url("__KP_FONT_TITILLIUM_URL__") format("opentype");
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

@font-face {
  font-family: "Cubellan";
  src: url("__KP_FONT_CUBELLAN_URL__") format("truetype");
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

@font-face {
  font-family: "Ezarion";
  src: url("__KP_FONT_EZARION_URL__") format("truetype");
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

@font-face {
  font-family: "Dosis";
  src: url("__KP_FONT_DOSIS_URL__") format("truetype");
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

/* Style isolation: all keyboard rules are scoped so host page CSS won't override them */
.kp-keybindings-ui {
  --kp-accent: #5be2f1;
}

/* ── Keyboard plate (pro app tray) ─────────────────────────────── */
.keyboard-visual.kp-keybindings-ui {
  --kp-kb-surface: #12151c;
  --kp-kb-well: #0a0c11;
  --kp-kb-rim: rgba(255, 255, 255, 0.08);
  box-sizing: border-box;
  width: 100%;
  padding: 5px;
  border-radius: 14px;
  border: 1px solid var(--kp-kb-rim);
  background:
    linear-gradient(180deg, rgba(255, 255, 255, 0.035) 0%, transparent 28%),
    radial-gradient(120% 80% at 50% 0%, rgba(91, 226, 241, 0.05) 0%, transparent 55%),
    linear-gradient(180deg, #161a22 0%, var(--kp-kb-surface) 45%, var(--kp-kb-well) 100%);
  box-shadow:
    0 1px 0 rgba(255, 255, 255, 0.06) inset,
    0 -1px 0 rgba(0, 0, 0, 0.45) inset,
    0 12px 28px rgba(0, 0, 0, 0.45),
    0 2px 0 rgba(0, 0, 0, 0.35);
  font-family: "Dosis", ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
  font-size: 10px;
  line-height: 1.1;
  user-select: none;
}

.kp-keybindings-ui .keyboard-row {
  display: flex;
  justify-content: center;
  align-items: stretch;
  margin-bottom: 7px;
  gap: 5px;
  width: 100%;
}

.kp-keybindings-ui .keyboard-row:last-child {
  margin-bottom: 0;
}

/* ── Base keycap: low-profile chiclet (flat + lightly realistic) ─ */
.kp-keybindings-ui .key {
  --kp-key-face: #3d4454;
  --kp-key-mid: #343a48;
  --kp-key-deep: #2c313e;
  --kp-key-icon: #1a1e28;
  --kp-key-glow: transparent;

  position: relative;
  box-sizing: border-box;
  margin: 0;
  font-family: inherit;
  font-size: inherit;
  line-height: inherit;
  cursor: default;
  appearance: none;
  -webkit-appearance: none;
  color: rgba(248, 250, 252, 0.94);
  text-align: center;
  overflow: hidden;

  /* Equal geometry for alphanumeric keys */
  flex: 1 1 0;
  min-width: 0;
  width: 0;
  height: 50px;
  min-height: 50px;
  max-height: 50px;
  /* Block layout: letter/name layers are absolutely positioned (not flex-flow) */
  display: block;
  padding: 0;
  border-radius: 7px;

  /*
   * Low-profile key: nearly flat face, thin rim, soft ground shadow.
   * Reads more like a real chiclet key than a heavy 3D bevel.
   */
  border: 1px solid rgba(0, 0, 0, 0.4);
  border-top-color: rgba(255, 255, 255, 0.1);
  border-bottom-color: rgba(0, 0, 0, 0.5);

  background:
    linear-gradient(180deg,
      rgba(255, 255, 255, 0.07) 0%,
      rgba(255, 255, 255, 0.02) 18%,
      transparent 42%),
    linear-gradient(180deg,
      var(--kp-key-face) 0%,
      var(--kp-key-mid) 70%,
      var(--kp-key-deep) 100%);

  box-shadow:
    0 1px 0 rgba(0, 0, 0, 0.45),
    0 2px 4px rgba(0, 0, 0, 0.22),
    inset 0 1px 0 rgba(255, 255, 255, 0.1),
    inset 0 -1px 0 rgba(0, 0, 0, 0.18);

  transition:
    transform 100ms ease,
    box-shadow 100ms ease,
    filter 100ms ease,
    border-color 100ms ease,
    background 100ms ease;
}

/* Minimal face sheen (not a tall sculpted plate) */
.kp-keybindings-ui .key::before {
  content: '';
  position: absolute;
  z-index: 0;
  top: 1px;
  left: 2px;
  right: 2px;
  height: 38%;
  border-radius: 5px 5px 40% 40%;
  background: linear-gradient(180deg,
    rgba(255, 255, 255, 0.08) 0%,
    rgba(255, 255, 255, 0.02) 60%,
    transparent 100%);
  pointer-events: none;
}

.kp-keybindings-ui [data-kp-action-id] {
  cursor: pointer;
}

.kp-keybindings-ui [data-kp-action-id]:hover {
  filter: brightness(1.07);
  border-top-color: rgba(255, 255, 255, 0.14);
  box-shadow:
    0 1px 0 rgba(0, 0, 0, 0.4),
    0 3px 8px rgba(0, 0, 0, 0.28),
    0 0 0 1px rgba(255, 255, 255, 0.04),
    0 0 10px var(--kp-key-glow),
    inset 0 1px 0 rgba(255, 255, 255, 0.12),
    inset 0 -1px 0 rgba(0, 0, 0, 0.16);
}

/*
 * Layered key legend (independent of each other):
 * - .key-main  = action name — upper band only
 * - .key-label = physical key letter — always pinned bottom-center
 * - .key-text  = special / unassigned glyph
 */
.kp-keybindings-ui .key > .key-main {
  position: absolute;
  z-index: 1;
  /* Pin action name to the top of the key face */
  top: 3px;
  left: 2px;
  right: 2px;
  bottom: auto;
  /* Leave a fixed bottom band for the letter; never push it */
  height: auto;
  max-height: 30px;
  box-sizing: border-box;
  margin: 0;
  padding: 0 1px;
  font-size: 11px;
  font-weight: 650;
  letter-spacing: 0.02em;
  line-height: 1.1;
  opacity: 0.9;
  text-transform: uppercase;
  color: rgba(248, 250, 252, 0.94);
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  word-break: break-word;
  hyphens: auto;
  text-align: center;
  pointer-events: none;
}

/* Letter / chrome labels: fixed bottom layer on every key */
.kp-keybindings-ui .key > .key-label,
.kp-keybindings-ui .key > .key-text {
  position: absolute;
  z-index: 2;
  left: 0;
  right: 0;
  bottom: 3px;
  top: auto;
  transform: none;
  box-sizing: border-box;
  margin: 0;
  padding: 0 2px;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1;
  text-align: center;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.45);
  pointer-events: none;
}

.kp-keybindings-ui .key > .key-label {
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 0.03em;
  color: var(--kp-accent, #5be2f1);
}

/* Special chrome labels (Tab/Caps/…) */
.kp-keybindings-ui .key > .key-text {
  font-size: 10px;
  font-weight: 650;
  letter-spacing: 0.02em;
  color: rgba(248, 250, 252, 0.92);
}

/* Unassigned letter-only keys: still bottom-centered (same letter layer) */
.kp-keybindings-ui .key:not([data-kp-action-id]):not(.key-tab):not(.key-caps):not(.key-enter):not(.key-shift):not(.key-backspace) > .key-text {
  bottom: 3px;
  top: auto;
  transform: none;
  font-size: 12px;
  font-weight: 700;
  color: var(--kp-accent, #5be2f1);
}

/* Special keys: wider, same height */
.kp-keybindings-ui .key.key-tab,
.kp-keybindings-ui .key.key-caps,
.kp-keybindings-ui .key.key-enter,
.kp-keybindings-ui .key.key-shift,
.kp-keybindings-ui .key.key-backspace {
  height: 50px;
  min-height: 50px;
  max-height: 50px;
  width: auto;
}

.kp-keybindings-ui .key.key-tab { flex: 1.25 1 0; }
.kp-keybindings-ui .key.key-caps { flex: 1.35 1 0; }
.kp-keybindings-ui .key.key-enter { flex: 1.55 1 0; }
.kp-keybindings-ui .key.key-shift { flex: 1.65 1 0; }
.kp-keybindings-ui .key.key-backspace { flex: 1.55 1 0; }

/* ── Color families (muted pro tints + darker icon color) ─────── */
.kp-keybindings-ui .key.key-activate,
.kp-keybindings-ui .key.key-activate-new,
.kp-keybindings-ui .key.key-activate-new-over,
.kp-keybindings-ui .key.key-tab-right,
.kp-keybindings-ui .key.key-new-tab,
.kp-keybindings-ui .key.key-open-popover,
.kp-keybindings-ui .key.key-preview-popover,
.kp-keybindings-ui .key.key-page-up,
.kp-keybindings-ui .key.key-page-down,
.kp-keybindings-ui .key.key-page-up-instant,
.kp-keybindings-ui .key.key-page-down-instant,
.kp-keybindings-ui .key.key-help,
.kp-keybindings-ui .key.key-omnibox {
  
  --kp-key-face: #2f8f5b;
  --kp-key-mid: #247a4c;
  --kp-key-deep: #17633a;
  --kp-key-icon: #0d3a22;
  --kp-key-glow: rgba(34, 197, 94, 0.18);

}

.kp-keybindings-ui .key.key-back,
.kp-keybindings-ui .key.key-forward,
.kp-keybindings-ui .key.key-scroll-top,
.kp-keybindings-ui .key.key-scroll-bottom {
  
  --kp-key-face: #2f7ea8;
  --kp-key-mid: #256b92;
  --kp-key-deep: #1a5475;
  --kp-key-icon: #0d3044;
  --kp-key-glow: rgba(56, 189, 248, 0.16);

}

.kp-keybindings-ui .key.key-delete,
.kp-keybindings-ui .key.key-close-tab {
  
  --kp-key-face: #b84a4a;
  --kp-key-mid: #9e3b3b;
  --kp-key-deep: #7a2b2b;
  --kp-key-icon: #401616;
  --kp-key-glow: rgba(248, 113, 113, 0.16);

}

/* Selection tools: indigo family (distinct from green activate / blue nav / amber unused) */
.kp-keybindings-ui .key.key-highlight,
.kp-keybindings-ui .key.key-rect-highlight {
  
  --kp-key-face: #5b6fd4;
  --kp-key-mid: #4a5cbb;
  --kp-key-deep: #3949a0;
  --kp-key-icon: #1a2258;
  --kp-key-glow: rgba(99, 102, 241, 0.18);

}

.kp-keybindings-ui .key.key-scroll {
  
  --kp-key-face: #7a5638;
  --kp-key-mid: #63452c;
  --kp-key-deep: #4a3320;
  --kp-key-icon: #26180f;
  --kp-key-glow: rgba(180, 120, 70, 0.12);

}

.kp-keybindings-ui .key.key-purple,
.kp-keybindings-ui .key.key-cols {
  
  --kp-key-face: #7a4ab8;
  --kp-key-mid: #663d9e;
  --kp-key-deep: #4e2e7a;
  --kp-key-icon: #281646;
  --kp-key-glow: rgba(167, 139, 250, 0.14);

}

.kp-keybindings-ui .key.key-orange {
  
  --kp-key-face: #c97a28;
  --kp-key-mid: #a8641e;
  --kp-key-deep: #834f16;
  --kp-key-icon: #3f250a;
  --kp-key-glow: rgba(255, 165, 0, 0.14);

}

.kp-keybindings-ui .key.key-launcher-orange {
  
  --kp-key-face: #a06a3a;
  --kp-key-mid: #85562e;
  --kp-key-deep: #664122;
  --kp-key-icon: #322010;
  --kp-key-glow: rgba(184, 115, 51, 0.12);

}

.kp-keybindings-ui .key.key-settings-dark {
  
  --kp-key-face: #3a4250;
  --kp-key-mid: #2a313c;
  --kp-key-deep: #1a1f28;
  --kp-key-icon: #0c0f14;
  --kp-key-glow: rgba(148, 163, 184, 0.1);

}

.kp-keybindings-ui .key.key-gray {
  
  --kp-key-face: #5a6270;
  --kp-key-mid: #484f5c;
  --kp-key-deep: #343a45;
  --kp-key-icon: #1a1e26;
  --kp-key-glow: rgba(148, 163, 184, 0.1);

}

.kp-keybindings-ui .key.key-launcher {
  
  --kp-key-face: #2a8fa3;
  --kp-key-mid: #22788a;
  --kp-key-deep: #185e6d;
  --kp-key-icon: #0c343c;
  --kp-key-glow: rgba(34, 211, 238, 0.14);

}

.kp-keybindings-ui .key.key-hatched {
  position: relative;
}

.kp-keybindings-ui .key.key-hatched::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    repeating-linear-gradient(
      45deg,
      rgba(200, 200, 200, 0.4) 0px,
      rgba(200, 200, 200, 0.4) 1px,
      transparent 1px,
      transparent 4px
    );
  pointer-events: none;
  border-radius: 4px;
}

.kp-keybindings-ui .key.key-radial-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at center,
    rgba(150, 150, 150, 0.3) 0%,
    rgba(120, 120, 120, 0.25) 30%,
    transparent 70%);
  pointer-events: none;
  border-radius: 4px;
}

.kp-keybindings-ui .key.key-checkerboard-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    radial-gradient(circle at 25% 25%, rgba(160, 160, 160, 0.3) 2px, transparent 2px),
    radial-gradient(circle at 75% 75%, rgba(160, 160, 160, 0.3) 2px, transparent 2px);
  background-size: 8px 8px;
  pointer-events: none;
  border-radius: 4px;
}

.kp-keybindings-ui .key.key-stripes-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    linear-gradient(90deg, transparent 0%, transparent 40%, rgba(180, 180, 180, 0.25) 40%, rgba(180, 180, 180, 0.25) 60%, transparent 60%);
  background-size: 6px 100%;
  pointer-events: none;
  border-radius: 4px;
}

.kp-keybindings-ui .key.key-crosshatch-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    repeating-linear-gradient(45deg, rgba(170, 170, 170, 0.25) 0px, rgba(170, 170, 170, 0.25) 1px, transparent 1px, transparent 4px),
    repeating-linear-gradient(-45deg, rgba(170, 170, 170, 0.25) 0px, rgba(170, 170, 170, 0.25) 1px, transparent 1px, transparent 4px);
  pointer-events: none;
  border-radius: 4px;
}

.kp-keybindings-ui .key.key-noise-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    linear-gradient(45deg, rgba(80, 80, 80, 0.2) 25%, transparent 25%),
    linear-gradient(-45deg, rgba(80, 80, 80, 0.2) 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, rgba(80, 80, 80, 0.2) 75%),
    linear-gradient(-45deg, transparent 75%, rgba(80, 80, 80, 0.2) 75%);
  background-size: 4px 4px;
  pointer-events: none;
  border-radius: 4px;
}

.kp-keybindings-ui .key.key-conic-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: conic-gradient(
    from 45deg,
    rgba(100, 100, 100, 0.2) 0deg,
    rgba(120, 120, 120, 0.25) 90deg,
    rgba(140, 140, 140, 0.2) 180deg,
    rgba(100, 100, 100, 0.2) 360deg
  );
  pointer-events: none;
  border-radius: 4px;
}

.kp-keybindings-ui .key.key-dashed-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  box-shadow: inset 0 0 0 2px rgba(140, 140, 140, 0.4);
  pointer-events: none;
  border-radius: 4px;
}

/*
 * Keydown/keyup press feedback is a dedicated .key-press-overlay element
 * (see ensureKeyPressOverlay / setKeyPressedState). Avoid filter/transform
 * on the key itself — those were hard to see on colored keycaps.
 */
.kp-keybindings-ui .key.kp-key-pressed {
  outline: none;
}

/*
 * Text mode: all keys grayed out by default. Click Element (ACTIVATE / F)
 * lights up only while the hover-click countdown is armed on a clickable.
 */
.kp-keybindings-ui.kp-text-mode-filter .key.kp-key-text-mode-disabled {
  opacity: 0.34;
  filter: grayscale(0.85) brightness(0.78);
  pointer-events: none;
  cursor: default;
}
.kp-keybindings-ui.kp-text-mode-filter .key.kp-key-text-mode-active {
  opacity: 1;
  filter: none;
  z-index: 2;
  outline: none;
  pointer-events: auto;
  cursor: pointer;
  border-color: rgba(255, 140, 0, 0.75) !important;
  box-shadow:
    0 0 0 2px rgba(255, 140, 0, 0.35),
    0 0 12px 2px rgba(255, 140, 0, 0.28),
    inset 0 0 0 1px rgba(255, 255, 255, 0.14) !important;
}

/*
 * Link-hover hint: when the page pointer is over a link and the keyboard
 * reference is open, highlight the keys that activate / open that link.
 */
.kp-keybindings-ui .key.kp-key-link-hint {
  z-index: 2;
  outline: none;
  filter: brightness(1.12) saturate(1.15);
  border-color: rgba(91, 226, 241, 0.85) !important;
  border-top-color: rgba(180, 245, 255, 0.95) !important;
  border-bottom-color: rgba(40, 180, 200, 0.9) !important;
  box-shadow:
    0 0 0 2px rgba(91, 226, 241, 0.55),
    0 0 14px 3px rgba(91, 226, 241, 0.55),
    0 0 28px 6px rgba(56, 189, 248, 0.28),
    0 1px 0 rgba(0, 0, 0, 0.35),
    inset 0 0 0 1px rgba(255, 255, 255, 0.22),
    inset 0 1px 0 rgba(255, 255, 255, 0.18) !important;
  animation: kp-key-link-hint-pulse 1.35s ease-in-out infinite;
}

@keyframes kp-key-link-hint-pulse {
  0%, 100% {
    box-shadow:
      0 0 0 2px rgba(91, 226, 241, 0.5),
      0 0 12px 2px rgba(91, 226, 241, 0.45),
      0 0 22px 4px rgba(56, 189, 248, 0.22),
      0 1px 0 rgba(0, 0, 0, 0.35),
      inset 0 0 0 1px rgba(255, 255, 255, 0.18),
      inset 0 1px 0 rgba(255, 255, 255, 0.14);
  }
  50% {
    box-shadow:
      0 0 0 3px rgba(120, 240, 255, 0.75),
      0 0 18px 5px rgba(91, 226, 241, 0.7),
      0 0 34px 10px rgba(56, 189, 248, 0.38),
      0 1px 0 rgba(0, 0, 0, 0.35),
      inset 0 0 0 1px rgba(255, 255, 255, 0.28),
      inset 0 1px 0 rgba(255, 255, 255, 0.2);
  }
}

/* Popover (tooltip) — matches the hovered key material via CSS vars.
 * Uses the HTML Popover API (top layer) so it can escape the keyboard panel's
 * overflow:hidden and sit above/below keys outside the panel bounds.
 *
 * Do NOT set inset with !important: that locks left/top longhands and beats
 * JS style.left/top, pinning every tooltip at the viewport origin. Override UA
 * popover defaults with non-important longhands + margin:0 instead. */
.kp-keybindings-popover {
  --kp-key-face: #3d4454;
  --kp-key-mid: #343a48;
  --kp-key-deep: #2c313e;
  --kp-key-icon: #1a1e28;

  position: fixed !important;
  /* Kill UA popover centering (inset 0 / margin auto) without locking longhands. */
  margin: 0 !important;
  top: auto;
  right: auto;
  bottom: auto;
  left: auto;
  width: max-content;
  height: fit-content;
  overflow: visible;
  box-sizing: border-box;

  z-index: 2147483046;
  max-width: min(300px, calc(100vw - 20px));
  min-width: 160px;
  color: rgba(248, 250, 252, 0.95);
  border-radius: 8px;
  padding: 10px 12px;
  font-size: 12px;
  line-height: 1.35;
  pointer-events: none; /* hover tooltips shouldn't steal pointer */

  /* Same low-profile key face treatment as .key */
  border: 1px solid rgba(0, 0, 0, 0.4);
  border-top-color: rgba(255, 255, 255, 0.12);
  border-bottom-color: rgba(0, 0, 0, 0.5);
  background:
    linear-gradient(180deg,
      rgba(255, 255, 255, 0.08) 0%,
      rgba(255, 255, 255, 0.02) 18%,
      transparent 42%),
    linear-gradient(180deg,
      var(--kp-key-face) 0%,
      var(--kp-key-mid) 70%,
      var(--kp-key-deep) 100%);
  box-shadow:
    0 1px 0 rgba(0, 0, 0, 0.45),
    0 10px 24px rgba(0, 0, 0, 0.4),
    inset 0 1px 0 rgba(255, 255, 255, 0.1),
    inset 0 -1px 0 rgba(0, 0, 0, 0.18);
}

/* Closed: both attribute + Popover API states */
.kp-keybindings-popover:not(:popover-open):not([data-kp-popover-open="true"]),
.kp-keybindings-popover[hidden] {
  display: none !important;
}

/* Open via Popover API or legacy fallback flag */
.kp-keybindings-popover:popover-open,
.kp-keybindings-popover[data-kp-popover-open="true"] {
  display: block;
  /* Re-assert after :popover-open (UA may reapply margin/inset). */
  margin: 0 !important;
  position: fixed !important;
}

.kp-keybindings-popover .kp-popover-head {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin: 0 0 6px 0;
}

.kp-keybindings-popover .kp-popover-icon {
  flex: 0 0 auto;
  width: 28px;
  height: 28px;
  border-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-top-color: rgba(255, 255, 255, 0.1);
  /* Glyph uses same darker icon color as keys */
  background-color: var(--kp-key-icon);
  background-image: none;
  background-repeat: no-repeat;
  background-position: center;
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  -webkit-mask-position: center;
  mask-position: center;
  -webkit-mask-size: 62% 62%;
  mask-size: 62% 62%;
  box-shadow:
    inset 0 1px 0 rgba(255, 255, 255, 0.08),
    inset 0 -1px 0 rgba(0, 0, 0, 0.2);
}

.kp-keybindings-popover .kp-popover-icon[hidden] {
  display: none;
}

.kp-keybindings-popover .kp-popover-title-wrap {
  min-width: 0;
  flex: 1 1 auto;
}

.kp-keybindings-popover .kp-popover-title {
  font-weight: 700;
  margin: 0 0 3px 0;
  color: rgba(248, 250, 252, 0.96);
  letter-spacing: 0.01em;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.35);
}

.kp-keybindings-popover .kp-popover-keys {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  color: rgba(255, 255, 255, 0.72);
  margin: 0;
  font-size: 11px;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.25);
}

.kp-keybindings-popover .kp-popover-desc {
  margin: 0;
  color: rgba(248, 250, 252, 0.9);
  opacity: 0.95;
  font-size: 11.5px;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.25);
}

.kp-keybindings-popover::before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  left: var(--kp-arrow-left, 18px);
  border: 9px solid transparent;
}

.kp-keybindings-popover[data-placement="top"]::before {
  top: 100%;
  border-top-color: rgba(0, 0, 0, 0.45);
}

.kp-keybindings-popover[data-placement="top"]::after {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  left: var(--kp-arrow-left, 18px);
  top: calc(100% - 1px);
  border: 8px solid transparent;
  border-top-color: var(--kp-key-deep);
}

.kp-keybindings-popover[data-placement="bottom"]::before {
  bottom: 100%;
  border-bottom-color: rgba(255, 255, 255, 0.12);
}

.kp-keybindings-popover[data-placement="bottom"]::after {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  left: var(--kp-arrow-left, 18px);
  bottom: calc(100% - 1px);
  border: 8px solid transparent;
  border-bottom-color: var(--kp-key-face);
}

/* Font Awesome-style faded key background icons (behind white labels) */

.kp-keybindings-ui .key > .key-bg-icon {
  position: absolute;
  inset: 7%;
  z-index: 0;
  pointer-events: none;
  /*
   * Transparent until an action rule applies both a mask and paint color.
   * mask-image:none + solid background-color otherwise paints a dark rectangle
   * (was visible on unmapped action keys like COPY_HOVERED_IMAGE before its icon).
   */
  background-color: transparent;
  background-image: none;
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  -webkit-mask-position: center center;
  mask-position: center center;
  -webkit-mask-size: 86% 86%;
  mask-size: 86% 86%;
  -webkit-mask-image: none;
  mask-image: none;
  opacity: 0.92;
}

/*
 * IMPORTANT: do NOT force position:relative on all non-icon children.
 * Action names (.key-main) and letter labels (.key-label) are absolutely
 * layered; a later relative rule would put letters back into flex flow.
 */

.kp-keybindings-ui .key:hover > .key-bg-icon {
  opacity: 1;
}

/* Keys without functions never paint an icon layer */
.kp-keybindings-ui .key:not([data-kp-action-id]) > .key-bg-icon {
  display: none;
}

/* Solid darken overlay for keydown feedback (more reliable than filter) */
.kp-keybindings-ui .key > .key-press-overlay {
  position: absolute;
  inset: 0;
  z-index: 6;
  box-sizing: border-box;
  border-radius: inherit;
  background: rgba(0, 0, 0, 0.78);
  opacity: 0;
  pointer-events: none;
  transition: opacity 70ms ease;
}

.kp-keybindings-ui .key.kp-key-pressed > .key-press-overlay,
.kp-keybindings-ui .key > .key-press-overlay.is-on {
  opacity: 1;
}

.kp-keybindings-ui .key[data-kp-action-id="ACTIVATE"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M320%200c17.7%200%2032%2014.3%2032%2032V176h16c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H352v16c0%2017.7-14.3%2032-32%2032s-32-14.3-32-32V240H272v16c0%2017.7-14.3%2032-32%2032s-32-14.3-32-32V240H192v80c0%2053%2043%2096%2096%2096h32c53%200%2096-43%2096-96V224h32c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H416V32c0-17.7-14.3-32-32-32H320zM192%2096c0-17.7-14.3-32-32-32H128C57.3%2064%200%20121.3%200%20192v96c0%2053%2043%2096%2096%2096h32c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H96c-17.7%200-32-14.3-32-32V192c0-35.3%2028.7-64%2064-64h32c17.7%200%2032-14.3%2032-32z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M320%200c17.7%200%2032%2014.3%2032%2032V176h16c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H352v16c0%2017.7-14.3%2032-32%2032s-32-14.3-32-32V240H272v16c0%2017.7-14.3%2032-32%2032s-32-14.3-32-32V240H192v80c0%2053%2043%2096%2096%2096h32c53%200%2096-43%2096-96V224h32c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H416V32c0-17.7-14.3-32-32-32H320zM192%2096c0-17.7-14.3-32-32-32H128C57.3%2064%200%20121.3%200%20192v96c0%2053%2043%2096%2096%2096h32c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H96c-17.7%200-32-14.3-32-32V192c0-35.3%2028.7-64%2064-64h32c17.7%200%2032-14.3%2032-32z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="ACTIVATE_NEW_TAB"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M320%200c-17.7%200-32%2014.3-32%2032s14.3%2032%2032%2032h82.7L201.4%20265.4c-12.5%2012.5-12.5%2032.8%200%2045.3s32.8%2012.5%2045.3%200L448%20109.3V192c0%2017.7%2014.3%2032%2032%2032s32-14.3%2032-32V32c0-17.7-14.3-32-32-32H320zM80%2032C35.8%2032%200%2067.8%200%20112V432c0%2044.2%2035.8%2080%2080%2080H400c44.2%200%2080-35.8%2080-80V320c0-17.7-14.3-32-32-32s-32%2014.3-32%2032V432c0%208.8-7.2%2016-16%2016H80c-8.8%200-16-7.2-16-16V112c0-8.8%207.2-16%2016-16H192c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H80z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M320%200c-17.7%200-32%2014.3-32%2032s14.3%2032%2032%2032h82.7L201.4%20265.4c-12.5%2012.5-12.5%2032.8%200%2045.3s32.8%2012.5%2045.3%200L448%20109.3V192c0%2017.7%2014.3%2032%2032%2032s32-14.3%2032-32V32c0-17.7-14.3-32-32-32H320zM80%2032C35.8%2032%200%2067.8%200%20112V432c0%2044.2%2035.8%2080%2080%2080H400c44.2%200%2080-35.8%2080-80V320c0-17.7-14.3-32-32-32s-32%2014.3-32%2032V432c0%208.8-7.2%2016-16%2016H80c-8.8%200-16-7.2-16-16V112c0-8.8%207.2-16%2016-16H192c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H80z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="ACTIVATE_NEW_TAB_BACKGROUND"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M64%20464H288c8.8%200%2016-7.2%2016-16V384h48v64c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V224c0-35.3%2028.7-64%2064-64h64v48H64c-8.8%200-16%207.2-16%2016V448c0%208.8%207.2%2016%2016%2016zM224%200c-35.3%200-64%2028.7-64%2064V288c0%2035.3%2028.7%2064%2064%2064H448c35.3%200%2064-28.7%2064-64V64c0-35.3-28.7-64-64-64H224zm0%2048H448c8.8%200%2016%207.2%2016%2016V288c0%208.8-7.2%2016-16%2016H224c-8.8%200-16-7.2-16-16V64c0-8.8%207.2-16%2016-16z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M64%20464H288c8.8%200%2016-7.2%2016-16V384h48v64c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V224c0-35.3%2028.7-64%2064-64h64v48H64c-8.8%200-16%207.2-16%2016V448c0%208.8%207.2%2016%2016%2016zM224%200c-35.3%200-64%2028.7-64%2064V288c0%2035.3%2028.7%2064%2064%2064H448c35.3%200%2064-28.7%2064-64V64c0-35.3-28.7-64-64-64H224zm0%2048H448c8.8%200%2016%207.2%2016%2016V288c0%208.8-7.2%2016-16%2016H224c-8.8%200-16-7.2-16-16V64c0-8.8%207.2-16%2016-16z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="BACK"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M9.4%20233.4c-12.5%2012.5-12.5%2032.8%200%2045.3l192%20192c12.5%2012.5%2032.8%2012.5%2045.3%200s12.5-32.8%200-45.3L109.3%20288%20480%20288c17.7%200%2032-14.3%2032-32s-14.3-32-32-32l-370.7%200%20137.4-137.4c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200l-192%20192z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M9.4%20233.4c-12.5%2012.5-12.5%2032.8%200%2045.3l192%20192c12.5%2012.5%2032.8%2012.5%2045.3%200s12.5-32.8%200-45.3L109.3%20288%20480%20288c17.7%200%2032-14.3%2032-32s-14.3-32-32-32l-370.7%200%20137.4-137.4c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200l-192%20192z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="BACK2"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M9.4%20233.4c-12.5%2012.5-12.5%2032.8%200%2045.3l192%20192c12.5%2012.5%2032.8%2012.5%2045.3%200s12.5-32.8%200-45.3L109.3%20288%20480%20288c17.7%200%2032-14.3%2032-32s-14.3-32-32-32l-370.7%200%20137.4-137.4c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200l-192%20192z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M9.4%20233.4c-12.5%2012.5-12.5%2032.8%200%2045.3l192%20192c12.5%2012.5%2032.8%2012.5%2045.3%200s12.5-32.8%200-45.3L109.3%20288%20480%20288c17.7%200%2032-14.3%2032-32s-14.3-32-32-32l-370.7%200%20137.4-137.4c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200l-192%20192z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="FORWARD"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M502.6%20278.6c12.5-12.5%2012.5-32.8%200-45.3l-192-192c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3L402.7%20224%2032%20224c-17.7%200-32%2014.3-32%2032s14.3%2032%2032%2032l370.7%200-137.4%20137.4c-12.5%2012.5-12.5%2032.8%200%2045.3s32.8%2012.5%2045.3%200l192-192z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M502.6%20278.6c12.5-12.5%2012.5-32.8%200-45.3l-192-192c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3L402.7%20224%2032%20224c-17.7%200-32%2014.3-32%2032s14.3%2032%2032%2032l370.7%200-137.4%20137.4c-12.5%2012.5-12.5%2032.8%200%2045.3s32.8%2012.5%2045.3%200l192-192z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="DELETE"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M135.2%2017.7L128%2032H32C14.3%2032%200%2046.3%200%2064S14.3%2096%2032%2096H480c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H384l-7.2-14.3C372.4%206.8%20361.3%200%20349.2%200H162.8c-12.1%200-23.2%206.8-28.6%2017.7zM32%20128V448c0%2035.3%2028.7%2064%2064%2064H416c35.3%200%2064-28.7%2064-64V128H32zm112%2064c8.8%200%2016%207.2%2016%2016V400c0%208.8-7.2%2016-16%2016s-16-7.2-16-16V208c0-8.8%207.2-16%2016-16zm96%200c8.8%200%2016%207.2%2016%2016V400c0%208.8-7.2%2016-16%2016s-16-7.2-16-16V208c0-8.8%207.2-16%2016-16zm96%200c8.8%200%2016%207.2%2016%2016V400c0%208.8-7.2%2016-16%2016s-16-7.2-16-16V208c0-8.8%207.2-16%2016-16z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M135.2%2017.7L128%2032H32C14.3%2032%200%2046.3%200%2064S14.3%2096%2032%2096H480c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H384l-7.2-14.3C372.4%206.8%20361.3%200%20349.2%200H162.8c-12.1%200-23.2%206.8-28.6%2017.7zM32%20128V448c0%2035.3%2028.7%2064%2064%2064H416c35.3%200%2064-28.7%2064-64V128H32zm112%2064c8.8%200%2016%207.2%2016%2016V400c0%208.8-7.2%2016-16%2016s-16-7.2-16-16V208c0-8.8%207.2-16%2016-16zm96%200c8.8%200%2016%207.2%2016%2016V400c0%208.8-7.2%2016-16%2016s-16-7.2-16-16V208c0-8.8%207.2-16%2016-16zm96%200c8.8%200%2016%207.2%2016%2016V400c0%208.8-7.2%2016-16%2016s-16-7.2-16-16V208c0-8.8%207.2-16%2016-16z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="COLS_TOGGLE"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M0%2096C0%2060.7%2028.7%2032%2064%2032H448c35.3%200%2064%2028.7%2064%2064V416c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V96zm64%2064V416H224V160H64zm320%200H288V416H448V160z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M0%2096C0%2060.7%2028.7%2032%2064%2032H448c35.3%200%2064%2028.7%2064%2064V416c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V96zm64%2064V416H224V160H64zm320%200H288V416H448V160z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="TAB_LEFT"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M41.4%20233.4c-12.5%2012.5-12.5%2032.8%200%2045.3l160%20160c12.5%2012.5%2032.8%2012.5%2045.3%200s12.5-32.8%200-45.3L109.3%20256%20246.6%20118.6c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200l-160%20160z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M41.4%20233.4c-12.5%2012.5-12.5%2032.8%200%2045.3l160%20160c12.5%2012.5%2032.8%2012.5%2045.3%200s12.5-32.8%200-45.3L109.3%20256%20246.6%20118.6c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200l-160%20160z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="TAB_RIGHT"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M470.6%20278.6c12.5-12.5%2012.5-32.8%200-45.3l-160-160c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3L402.7%20256%20265.4%20393.4c-12.5%2012.5-12.5%2032.8%200%2045.3s32.8%2012.5%2045.3%200l160-160z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M470.6%20278.6c12.5-12.5%2012.5-32.8%200-45.3l-160-160c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3L402.7%20256%20265.4%20393.4c-12.5%2012.5-12.5%2032.8%200%2045.3s32.8%2012.5%2045.3%200l160-160z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="ROOT"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M575.8%20255.5c0%2018-15%2032.1-32%2032.1h-32l.7%20160.2c.2%2035.5-28.5%2064.3-64%2064.3H392c-22.1%200-40-17.9-40-40V448%20384c0-17.7-14.3-32-32-32H256c-17.7%200-32%2014.3-32%2032v64%2024c0%2022.1-17.9%2040-40%2040H128.1c-35.3%200-64-28.7-64-64V287.6H32c-18%200-32-14-32-32.1c0-9%203-17%2010-24L266.4%208c7-7%2015-8%2022-8s15%202%2021%207L564.8%20231.5c8%207%2012%2015%2011%2024z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M575.8%20255.5c0%2018-15%2032.1-32%2032.1h-32l.7%20160.2c.2%2035.5-28.5%2064.3-64%2064.3H392c-22.1%200-40-17.9-40-40V448%20384c0-17.7-14.3-32-32-32H256c-17.7%200-32%2014.3-32%2032v64%2024c0%2022.1-17.9%2040-40%2040H128.1c-35.3%200-64-28.7-64-64V287.6H32c-18%200-32-14-32-32.1c0-9%203-17%2010-24L266.4%208c7-7%2015-8%2022-8s15%202%2021%207L564.8%20231.5c8%207%2012%2015%2011%2024z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="LAUNCHER"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M156.6%20384.9L125.7%20354c-8.5-8.5-11.5-20.8-7.7-32.2c3-8.9%207-20.5%2011.8-33.8L24%20288c-8.6%200-16.6-4.6-20.9-12.1s-4.2-16.7%20.2-24.1l52.5-88.5c13-21.9%2036.5-35.3%2061.9-35.3h82.3c2.4-4%204.8-7.7%207.2-11.3C289.1-4.1%20411.1-8.1%20483.9%205.3c11.6%202.1%2020.6%2011.2%2022.8%2022.8c13.4%2072.9%209.3%20194.8-111.4%20276.7c-3.5%202.4-7.3%204.8-11.3%207.2v82.3c0%2025.4-13.4%2049-35.3%2061.9l-88.5%2052.5c-7.4%204.4-16.6%204.5-24.1%20.2s-12.1-12.2-12.1-20.9V384.9c-13.3%204.8-24.9%208.8-33.8%2011.8c-11.4%203.7-23.7%20.7-32.2-7.8zM215.3%20237.3c28.3-28.3%2073.1-31.3%20105.4-8.5L200.5%20348.5c-22.8-32.3-19.8-77.1%208.5-105.4l6.3-5.8z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M156.6%20384.9L125.7%20354c-8.5-8.5-11.5-20.8-7.7-32.2c3-8.9%207-20.5%2011.8-33.8L24%20288c-8.6%200-16.6-4.6-20.9-12.1s-4.2-16.7%20.2-24.1l52.5-88.5c13-21.9%2036.5-35.3%2061.9-35.3h82.3c2.4-4%204.8-7.7%207.2-11.3C289.1-4.1%20411.1-8.1%20483.9%205.3c11.6%202.1%2020.6%2011.2%2022.8%2022.8c13.4%2072.9%209.3%20194.8-111.4%20276.7c-3.5%202.4-7.3%204.8-11.3%207.2v82.3c0%2025.4-13.4%2049-35.3%2061.9l-88.5%2052.5c-7.4%204.4-16.6%204.5-24.1%20.2s-12.1-12.2-12.1-20.9V384.9c-13.3%204.8-24.9%208.8-33.8%2011.8c-11.4%203.7-23.7%20.7-32.2-7.8zM215.3%20237.3c28.3-28.3%2073.1-31.3%20105.4-8.5L200.5%20348.5c-22.8-32.3-19.8-77.1%208.5-105.4l6.3-5.8z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="CLOSE_TAB"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%2048a208%20208%200%201%201%200%20416%20208%20208%200%201%201%200-416zm0%20464A256%20256%200%201%200%20256%200a256%20256%200%201%200%200%20512zM175%20175c9.4-9.4%2024.6-9.4%2033.9%200l47%2047%2047-47c9.4-9.4%2024.6-9.4%2033.9%200s9.4%2024.6%200%2033.9l-47%2047%2047%2047c9.4%209.4%209.4%2024.6%200%2033.9s-24.6%209.4-33.9%200l-47-47-47%2047c-9.4%209.4-24.6%209.4-33.9%200s-9.4-24.6%200-33.9l47-47-47-47c-9.4-9.4-9.4-24.6%200-33.9z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%2048a208%20208%200%201%201%200%20416%20208%20208%200%201%201%200-416zm0%20464A256%20256%200%201%200%20256%200a256%20256%200%201%200%200%20512zM175%20175c9.4-9.4%2024.6-9.4%2033.9%200l47%2047%2047-47c9.4-9.4%2024.6-9.4%2033.9%200s9.4%2024.6%200%2033.9l-47%2047%2047%2047c9.4%209.4%209.4%2024.6%200%2033.9s-24.6%209.4-33.9%200l-47-47-47%2047c-9.4%209.4-24.6%209.4-33.9%200s-9.4-24.6%200-33.9l47-47-47-47c-9.4-9.4-9.4-24.6%200-33.9z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="CANCEL"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%20512A256%20256%200%201%200%20256%200a256%20256%200%201%200%200%20512zM175%20175c9.4-9.4%2024.6-9.4%2033.9%200L368%20334.1c9.4%209.4%209.4%2024.6%200%2033.9s-24.6%209.4-33.9%200L175%20208.9c-9.4-9.4-9.4-24.6%200-33.9z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%20512A256%20256%200%201%200%20256%200a256%20256%200%201%200%200%20512zM175%20175c9.4-9.4%2024.6-9.4%2033.9%200L368%20334.1c9.4%209.4%209.4%2024.6%200%2033.9s-24.6%209.4-33.9%200L175%20208.9c-9.4-9.4-9.4-24.6%200-33.9z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="PAGE_UP_INSTANT"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20105.4c12.5-12.5%2032.8-12.5%2045.3%200l192%20192c12.5%2012.5%2012.5%2032.8%200%2045.3s-32.8%2012.5-45.3%200L256%20173.3%2086.6%20342.6c-12.5%2012.5-32.8%2012.5-45.3%200s-12.5-32.8%200-45.3l192-192z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20105.4c12.5-12.5%2032.8-12.5%2045.3%200l192%20192c12.5%2012.5%2012.5%2032.8%200%2045.3s-32.8%2012.5-45.3%200L256%20173.3%2086.6%20342.6c-12.5%2012.5-32.8%2012.5-45.3%200s-12.5-32.8%200-45.3l192-192z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="PAGE_DOWN_INSTANT"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20406.6c12.5%2012.5%2032.8%2012.5%2045.3%200l192-192c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200L256%20338.7%2086.6%20169.4c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3l192%20192z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20406.6c12.5%2012.5%2032.8%2012.5%2045.3%200l192-192c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200L256%20338.7%2086.6%20169.4c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3l192%20192z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="PAGE_TOP"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20105.4c12.5-12.5%2032.8-12.5%2045.3%200l96%2096c12.5%2012.5%2012.5%2032.8%200%2045.3s-32.8%2012.5-45.3%200L288%20205.3V384c0%2017.7-14.3%2032-32%2032s-32-14.3-32-32V205.3l-41.4%2041.4c-12.5%2012.5-32.8%2012.5-45.3%200s-12.5-32.8%200-45.3l96-96zM64%20448c0-17.7%2014.3-32%2032-32H416c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H96c-17.7%200-32-14.3-32-32z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20105.4c12.5-12.5%2032.8-12.5%2045.3%200l96%2096c12.5%2012.5%2012.5%2032.8%200%2045.3s-32.8%2012.5-45.3%200L288%20205.3V384c0%2017.7-14.3%2032-32%2032s-32-14.3-32-32V205.3l-41.4%2041.4c-12.5%2012.5-32.8%2012.5-45.3%200s-12.5-32.8%200-45.3l96-96zM64%20448c0-17.7%2014.3-32%2032-32H416c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H96c-17.7%200-32-14.3-32-32z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="PAGE_BOTTOM"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20406.6c12.5%2012.5%2032.8%2012.5%2045.3%200l96-96c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200L288%20306.7V128c0-17.7-14.3-32-32-32s-32%2014.3-32%2032V306.7l-41.4-41.4c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3l96%2096zM64%2064c0-17.7%2014.3-32%2032-32H416c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H96C78.3%2096%2064%2081.7%2064%2064z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M233.4%20406.6c12.5%2012.5%2032.8%2012.5%2045.3%200l96-96c12.5-12.5%2012.5-32.8%200-45.3s-32.8-12.5-45.3%200L288%20306.7V128c0-17.7-14.3-32-32-32s-32%2014.3-32%2032V306.7l-41.4-41.4c-12.5-12.5-32.8-12.5-45.3%200s-12.5%2032.8%200%2045.3l96%2096zM64%2064c0-17.7%2014.3-32%2032-32H416c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H96C78.3%2096%2064%2081.7%2064%2064z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="NEW_TAB"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M64%2032C28.7%2032%200%2060.7%200%2096V416c0%2035.3%2028.7%2064%2064%2064H448c35.3%200%2064-28.7%2064-64V160c0-35.3-28.7-64-64-64H298.5c-17%200-33.3-6.7-45.3-18.7L226.7%2050.7C214.7%2038.7%20198.5%2032%20181.5%2032H64zM232%20248v-48c0-13.3%2010.7-24%2024-24s24%2010.7%2024%2024v48h48c13.3%200%2024%2010.7%2024%2024s-10.7%2024-24%2024H280v48c0%2013.3-10.7%2024-24%2024s-24-10.7-24-24V296H184c-13.3%200-24-10.7-24-24s10.7-24%2024-24h48z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M64%2032C28.7%2032%200%2060.7%200%2096V416c0%2035.3%2028.7%2064%2064%2064H448c35.3%200%2064-28.7%2064-64V160c0-35.3-28.7-64-64-64H298.5c-17%200-33.3-6.7-45.3-18.7L226.7%2050.7C214.7%2038.7%20198.5%2032%20181.5%2032H64zM232%20248v-48c0-13.3%2010.7-24%2024-24s24%2010.7%2024%2024v48h48c13.3%200%2024%2010.7%2024%2024s-10.7%2024-24%2024H280v48c0%2013.3-10.7%2024-24%2024s-24-10.7-24-24V296H184c-13.3%200-24-10.7-24-24s10.7-24%2024-24h48z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="OPEN_POPOVER"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M64%2032C28.7%2032%200%2060.7%200%2096V416c0%2035.3%2028.7%2064%2064%2064H448c35.3%200%2064-28.7%2064-64V96c0-35.3-28.7-64-64-64H64zm32%2096H416c17.7%200%2032%2014.3%2032%2032v32H64V160c0-17.7%2014.3-32%2032-32z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M64%2032C28.7%2032%200%2060.7%200%2096V416c0%2035.3%2028.7%2064%2064%2064H448c35.3%200%2064-28.7%2064-64V96c0-35.3-28.7-64-64-64H64zm32%2096H416c17.7%200%2032%2014.3%2032%2032v32H64V160c0-17.7%2014.3-32%2032-32z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="PREVIEW_LINK_POPOVER"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%2096c-89.6%200-168.5%2048.8-212.7%20122.3c-7.3%2012.1-7.3%2027.3%200%2039.4C87.5%20331.2%20166.4%20380%20256%20380s168.5-48.8%20212.7-122.3c7.3-12.1%207.3-27.3%200-39.4C424.5%20144.8%20345.6%2096%20256%2096zm0%20224a96%2096%200%201%201%200-192%2096%2096%200%201%201%200%20192zm0-144a48%2048%200%201%200%200%2096%2048%2048%200%201%200%200-96z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%2096c-89.6%200-168.5%2048.8-212.7%20122.3c-7.3%2012.1-7.3%2027.3%200%2039.4C87.5%20331.2%20166.4%20380%20256%20380s168.5-48.8%20212.7-122.3c7.3-12.1%207.3-27.3%200-39.4C424.5%20144.8%20345.6%2096%20256%2096zm0%20224a96%2096%200%201%201%200-192%2096%2096%200%201%201%200%20192zm0-144a48%2048%200%201%200%200%2096%2048%2048%200%201%200%200-96z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="OPEN_SETTINGS_POPOVER"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M495.9%20166.1c3.3%2012.7%20.9%2026.3-7.1%2036.1l-37.3%2045.7c2.1%2011.1%203.2%2022.6%203.2%2034.3s-1.1%2023.2-3.2%2034.3l37.3%2045.7c8%209.8%2010.4%2023.4%207.1%2036.1c-6.3%2024.2-17.7%2046.6-33.1%2066.3c-8.1%2010.3-21.2%2014.9-33.9%2012.1l-57.5-12.7c-17.9%2015.3-38.4%2027.3-60.7%2035.4l-13.7%2057.5c-2.9%2012.1-12.9%2021.1-25.4%2022.4c-24.2%202.6-49.1%202.6-73.3%200c-12.5-1.3-22.5-10.3-25.4-22.4l-13.7-57.5c-22.3-8.1-42.8-20.1-60.7-35.4L71.6%20436.6c-12.7%202.8-25.8-1.8-33.9-12.1C22.3%20404.8%2010.9%20382.4%204.6%20358.2c-3.3-12.7-.9-26.3%207.1-36.1l37.3-45.7C46.9%20265.2%2045.8%20253.7%2045.8%20242s1.1-23.2%203.2-34.3L11.7%20161.9c-8-9.8-10.4-23.4-7.1-36.1C10.9%20101.6%2022.3%2079.2%2037.7%2059.5c8.1-10.3%2021.2-14.9%2033.9-12.1l57.5%2012.7c17.9-15.3%2038.4-27.3%2060.7-35.4L203.5-32.8c2.9-12.1%2012.9-21.1%2025.4-22.4c24.2-2.6%2049.1-2.6%2073.3%200c12.5%201.3%2022.5%2010.3%2025.4%2022.4l13.7%2057.5c22.3%208.1%2042.8%2020.1%2060.7%2035.4l57.5-12.7c12.7-2.8%2025.8%201.8%2033.9%2012.1c15.4%2019.7%2026.8%2042.1%2033.1%2066.3zM256%20336a80%2080%200%201%200%200-160%2080%2080%200%201%200%200%20160z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M495.9%20166.1c3.3%2012.7%20.9%2026.3-7.1%2036.1l-37.3%2045.7c2.1%2011.1%203.2%2022.6%203.2%2034.3s-1.1%2023.2-3.2%2034.3l37.3%2045.7c8%209.8%2010.4%2023.4%207.1%2036.1c-6.3%2024.2-17.7%2046.6-33.1%2066.3c-8.1%2010.3-21.2%2014.9-33.9%2012.1l-57.5-12.7c-17.9%2015.3-38.4%2027.3-60.7%2035.4l-13.7%2057.5c-2.9%2012.1-12.9%2021.1-25.4%2022.4c-24.2%202.6-49.1%202.6-73.3%200c-12.5-1.3-22.5-10.3-25.4-22.4l-13.7-57.5c-22.3-8.1-42.8-20.1-60.7-35.4L71.6%20436.6c-12.7%202.8-25.8-1.8-33.9-12.1C22.3%20404.8%2010.9%20382.4%204.6%20358.2c-3.3-12.7-.9-26.3%207.1-36.1l37.3-45.7C46.9%20265.2%2045.8%20253.7%2045.8%20242s1.1-23.2%203.2-34.3L11.7%20161.9c-8-9.8-10.4-23.4-7.1-36.1C10.9%20101.6%2022.3%2079.2%2037.7%2059.5c8.1-10.3%2021.2-14.9%2033.9-12.1l57.5%2012.7c17.9-15.3%2038.4-27.3%2060.7-35.4L203.5-32.8c2.9-12.1%2012.9-21.1%2025.4-22.4c24.2-2.6%2049.1-2.6%2073.3%200c12.5%201.3%2022.5%2010.3%2025.4%2022.4l13.7%2057.5c22.3%208.1%2042.8%2020.1%2060.7%2035.4l57.5-12.7c12.7-2.8%2025.8%201.8%2033.9%2012.1c15.4%2019.7%2026.8%2042.1%2033.1%2066.3zM256%20336a80%2080%200%201%200%200-160%2080%2080%200%201%200%200%20160z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="OMNIBOX"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M416%20208c0%2045.9-14.9%2088.3-40%20122.7L502.6%20457.4c12.5%2012.5%2012.5%2032.8%200%2045.3s-32.8%2012.5-45.3%200L330.7%20376c-34.4%2025.2-76.8%2040-122.7%2040C93.1%20416%200%20322.9%200%20208S93.1%200%20208%200S416%2093.1%20416%20208zM208%20352a144%20144%200%201%200%200-288%20144%20144%200%201%200%200%20288z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M416%20208c0%2045.9-14.9%2088.3-40%20122.7L502.6%20457.4c12.5%2012.5%2012.5%2032.8%200%2045.3s-32.8%2012.5-45.3%200L330.7%20376c-34.4%2025.2-76.8%2040-122.7%2040C93.1%20416%200%20322.9%200%20208S93.1%200%20208%200S416%2093.1%20416%20208zM208%20352a144%20144%200%201%200%200-288%20144%20144%200%201%200%200%20288z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="TAB_HISTORY"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%200C114.6%200%200%20114.6%200%20256S114.6%20512%20256%20512c53%200%20102-16.2%20142.7-43.9c10.8-7.4%2013.6-22.3%206.2-33.1s-22.3-13.6-33.1-6.2C340.8%20449.1%20299.6%20464%20256%20464C141.1%20464%2048%20370.9%2048%20256S141.1%2048%20256%2048c60.7%200%20115.5%2026.1%20153.4%2067.7l-33.5%2033.5c-9.4%209.4-2.7%2025.5%2010.5%2025.5H456c13.3%200%2024-10.7%2024-24V56c0-13.2-16.1-19.9-25.5-10.5L418.7%2081.3C368.5%2031.4%20315.1%200%20256%200zM232%20120c0-13.3-10.7-24-24-24s-24%2010.7-24%2024V256c0%206.4%202.5%2012.5%207%2017l72%2072c9.4%209.4%2024.6%209.4%2033.9%200s9.4-24.6%200-33.9l-65-65V120z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M256%200C114.6%200%200%20114.6%200%20256S114.6%20512%20256%20512c53%200%20102-16.2%20142.7-43.9c10.8-7.4%2013.6-22.3%206.2-33.1s-22.3-13.6-33.1-6.2C340.8%20449.1%20299.6%20464%20256%20464C141.1%20464%2048%20370.9%2048%20256S141.1%2048%20256%2048c60.7%200%20115.5%2026.1%20153.4%2067.7l-33.5%2033.5c-9.4%209.4-2.7%2025.5%2010.5%2025.5H456c13.3%200%2024-10.7%2024-24V56c0-13.2-16.1-19.9-25.5-10.5L418.7%2081.3C368.5%2031.4%20315.1%200%20256%200zM232%20120c0-13.3-10.7-24-24-24s-24%2010.7-24%2024V256c0%206.4%202.5%2012.5%207%2017l72%2072c9.4%209.4%2024.6%209.4%2033.9%200s9.4-24.6%200-33.9l-65-65V120z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="TOGGLE_KEYBOARD_HELP"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M0%2096C0%2060.7%2028.7%2032%2064%2032H448c35.3%200%2064%2028.7%2064%2064V416c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V96zm128%2064v32h32V160H128zm64%200v32h32V160H192zm64%200v32h32V160H256zm64%200v32h32V160H320zm64%200v32h32V160H384zM96%20256v32h64V256H96zm96%200v32h32V256H192zm64%200v32h32V256H256zm64%200v32h32V256H320zm64%200v32h32V256H384zm64%200v32h32V256H448zM128%20352v32H384V352H128z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M0%2096C0%2060.7%2028.7%2032%2064%2032H448c35.3%200%2064%2028.7%2064%2064V416c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V96zm128%2064v32h32V160H128zm64%200v32h32V160H192zm64%200v32h32V160H256zm64%200v32h32V160H320zm64%200v32h32V160H384zM96%20256v32h64V256H96zm96%200v32h32V256H192zm64%200v32h32V256H256zm64%200v32h32V256H320zm64%200v32h32V256H384zm64%200v32h32V256H448zM128%20352v32H384V352H128z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="HIGHLIGHT"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M128%2064c0-17.7%2014.3-32%2032-32H352c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H288v128h64c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H288v128h64c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H160c-17.7%200-32-14.3-32-32s14.3-32%2032-32h64V288H160c-17.7%200-32-14.3-32-32s14.3-32%2032-32h64V96H160c-17.7%200-32-14.3-32-32z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M128%2064c0-17.7%2014.3-32%2032-32H352c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H288v128h64c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H288v128h64c17.7%200%2032%2014.3%2032%2032s-14.3%2032-32%2032H160c-17.7%200-32-14.3-32-32s14.3-32%2032-32h64V288H160c-17.7%200-32-14.3-32-32s14.3-32%2032-32h64V96H160c-17.7%200-32-14.3-32-32z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="RECTANGLE_HIGHLIGHT"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M32%2032C14.3%2032%200%2046.3%200%2064v64c0%2017.7%2014.3%2032%2032%2032s32-14.3%2032-32V96h64c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H32zM32%20320c-17.7%200-32%2014.3-32%2032v64c0%2017.7%2014.3%2032%2032%2032h64c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H64V352c0-17.7-14.3-32-32-32zM320%2064c0%2017.7%2014.3%2032%2032%2032h64v64c0%2017.7%2014.3%2032%2032%2032s32-14.3%2032-32V64c0-17.7-14.3-32-32-32H352c-17.7%200-32%2014.3-32%2032zM480%20320c-17.7%200-32%2014.3-32%2032v64H384c-17.7%200-32%2014.3-32%2032s14.3%2032%2032%2032h64c17.7%200%2032-14.3%2032-32V352c0-17.7-14.3-32-32-32z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M32%2032C14.3%2032%200%2046.3%200%2064v64c0%2017.7%2014.3%2032%2032%2032s32-14.3%2032-32V96h64c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H32zM32%20320c-17.7%200-32%2014.3-32%2032v64c0%2017.7%2014.3%2032%2032%2032h64c17.7%200%2032-14.3%2032-32s-14.3-32-32-32H64V352c0-17.7-14.3-32-32-32zM320%2064c0%2017.7%2014.3%2032%2032%2032h64v64c0%2017.7%2014.3%2032%2032%2032s32-14.3%2032-32V64c0-17.7-14.3-32-32-32H352c-17.7%200-32%2014.3-32%2032zM480%20320c-17.7%200-32%2014.3-32%2032v64H384c-17.7%200-32%2014.3-32%2032s14.3%2032%2032%2032h64c17.7%200%2032-14.3%2032-32V352c0-17.7-14.3-32-32-32z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }
.kp-keybindings-ui .key[data-kp-action-id="COPY_HOVERED_IMAGE"] > .key-bg-icon { -webkit-mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M0%2096C0%2060.7%2028.7%2032%2064%2032H448c35.3%200%2064%2028.7%2064%2064V416c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V96zM323.8%20202.5c-4.5-6.6-11.9-10.5-19.8-10.5s-15.4%203.9-19.8%2010.5l-87%20127.6L170.7%20297c-4.6-5.7-11.5-9-18.7-9s-14.2%203.3-18.7%209l-64%2080c-5.8%207.2-6.9%2017.1-2.9%2025.4s12.4%2013.6%2021.6%2013.6h96%2032H424c8.9%200%2017.1-4.9%2021.2-12.8s3.6-17.4-1.4-24.7l-120-176zM112%20192a48%2048%200%201%200%200-96%2048%2048%200%201%200%200%2096z%22%2F%3E%3C%2Fsvg%3E"); mask-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20512%20512%22%20fill%3D%22black%22%3E%3Cpath%20d%3D%22M0%2096C0%2060.7%2028.7%2032%2064%2032H448c35.3%200%2064%2028.7%2064%2064V416c0%2035.3-28.7%2064-64%2064H64c-35.3%200-64-28.7-64-64V96zM323.8%20202.5c-4.5-6.6-11.9-10.5-19.8-10.5s-15.4%203.9-19.8%2010.5l-87%20127.6L170.7%20297c-4.6-5.7-11.5-9-18.7-9s-14.2%203.3-18.7%209l-64%2080c-5.8%207.2-6.9%2017.1-2.9%2025.4s12.4%2013.6%2021.6%2013.6h96%2032H424c8.9%200%2017.1-4.9%2021.2-12.8s3.6-17.4-1.4-24.7l-120-176zM112%20192a48%2048%200%201%200%200-96%2048%2048%200%201%200%200%2096z%22%2F%3E%3C%2Fsvg%3E"); background-color: var(--kp-key-icon, #0c1018); }

/*
 * TEMP suspended: Floating Keyboard Reference flex-scale keys with panel resize.
 * Keys use the global fixed 50px keycap rules again. Re-enable together with
 * makePopoverResizable in floating-keyboard-help.js when resuming this work.
 *
 * .kp-floating-keyboard-help .kp-floating-keyboard-help__keyboard {
 *   box-sizing: border-box;
 *   flex: 1 1 auto;
 *   min-height: 0;
 *   width: 100%;
 *   height: 100%;
 *   display: flex;
 *   flex-direction: column;
 * }
 * .kp-floating-keyboard-help .keyboard-visual.kp-keybindings-ui {
 *   flex: 1 1 auto;
 *   min-height: 0;
 *   width: 100%;
 *   height: 100%;
 *   display: flex;
 *   flex-direction: column;
 *   gap: 7px;
 *   padding: clamp(4px, 1.2%, 10px);
 * }
 * .kp-floating-keyboard-help .kp-keybindings-ui .keyboard-row {
 *   flex: 1 1 0;
 *   min-height: 0;
 *   margin-bottom: 0;
 *   gap: clamp(3px, 0.7%, 7px);
 *   align-items: stretch;
 * }
 * .kp-floating-keyboard-help .kp-keybindings-ui .key,
 * .kp-floating-keyboard-help .kp-keybindings-ui .key.key-tab,
 * .kp-floating-keyboard-help .kp-keybindings-ui .key.key-caps,
 * .kp-floating-keyboard-help .kp-keybindings-ui .key.key-enter,
 * .kp-floating-keyboard-help .kp-keybindings-ui .key.key-shift,
 * .kp-floating-keyboard-help .kp-keybindings-ui .key.key-backspace {
 *   height: 100%;
 *   min-height: 0;
 *   max-height: none;
 *   border-radius: clamp(5px, 12%, 10px);
 *   container-type: size;
 *   container-name: kp-key;
 * }
 * .kp-floating-keyboard-help .kp-keybindings-ui .key > .key-main {
 *   font-size: clamp(9px, 18cqh, 15px);
 *   max-height: 55%;
 *   top: clamp(2px, 8cqh, 8px);
 * }
 * .kp-floating-keyboard-help .kp-keybindings-ui .key > .key-label {
 *   font-size: clamp(10px, 22cqh, 18px);
 *   bottom: clamp(2px, 8cqh, 8px);
 * }
 * .kp-floating-keyboard-help .kp-keybindings-ui .key > .key-text {
 *   font-size: clamp(9px, 18cqh, 15px);
 *   bottom: clamp(2px, 8cqh, 8px);
 * }
 */
`;

  // --- begin stamped onboarding-shared.js ---
  /**
   * Shared onboarding walkthrough primitives.
   *
   * Zero imports so this file can be:
   * - imported by ESM modules (panel / manager)
   * - stamped into early-inject.js by build.js (export keywords stripped)
   *
   * Keep DOM construction and progress shape here so early-inject and the
   * bundled content script cannot drift.
   */

  // ── Storage / progress ──────────────────────────────────────────────────────

  const ONBOARDING_STORAGE_KEYS = {
    ACTIVE: 'keypilot_onboarding_active',
    PROGRESS: 'keypilot_onboarding_progress'
  };

  const ONBOARDING_FIRST_SLIDE_ID = 'basic_navigation';
  const ONBOARDING_PANEL_CLASS = 'kp-onboarding-panel';
  const ONBOARDING_DEFAULT_TITLE = 'Welcome to KeyPilot';
  const ONBOARDING_REOPEN_TIP = 'Tip: Press Alt + / to re-open this walkthrough later.';

  /** Default z-index fallback if caller does not pass Z_INDEX.ONBOARDING_PANEL. */
  const ONBOARDING_PANEL_Z_FALLBACK = 2147483026;

  /** Layout: control strip stays at top; walkthrough sits just below it. */
  const ONBOARDING_DEFAULT_LEFT_PX = 16;
  const ONBOARDING_DEFAULT_TOP_PX = 16;
  /** Prefixed names avoid clashing with early-inject locals when this file is stamped. */
  const ONBOARDING_STRIP_TOP_PX = 16;
  const ONBOARDING_STRIP_HEIGHT_PX = 28;
  const ONBOARDING_BELOW_STRIP_GAP_PX = 8;

  /**
   * Preferred top offset for the walkthrough so the control strip stays visible above it.
   * @returns {number}
   */
  function getOnboardingTopBelowControlStrip() {
    try {
      const strip = document.querySelector('.kp-control-strip');
      if (strip && strip.isConnected) {
        const cs = typeof window.getComputedStyle === 'function' ? window.getComputedStyle(strip) : null;
        const hidden =
          strip.hidden === true ||
          strip.getAttribute('hidden') !== null ||
          (strip.style && strip.style.display === 'none') ||
          (cs && (cs.display === 'none' || cs.visibility === 'hidden'));
        if (!hidden) {
          const rect = strip.getBoundingClientRect();
          if (rect && rect.height > 0) {
            return Math.max(
              ONBOARDING_DEFAULT_TOP_PX,
              Math.round(rect.bottom + ONBOARDING_BELOW_STRIP_GAP_PX)
            );
          }
        }
      }
    } catch { /* ignore */ }
    // Fallback assuming strip is at its default top-left perch.
    return ONBOARDING_STRIP_TOP_PX + ONBOARDING_STRIP_HEIGHT_PX + ONBOARDING_BELOW_STRIP_GAP_PX;
  }

  /**
   * @param {HTMLElement|null} root
   */
  function positionOnboardingBelowControlStrip(root) {
    if (!root) return;
    try {
      root.style.top = `${getOnboardingTopBelowControlStrip()}px`;
    } catch { /* ignore */ }
  }

  /**
   * @typedef {Object} OnboardingProgress
   * @property {string|null} slideId
   * @property {string[]} completedTaskIds
   * @property {string[]} onEnterDoneSlideIds
   * @property {boolean} completed
   * @property {number} timestamp
   */

  /**
   * @param {string|null} [slideId]
   * @returns {OnboardingProgress}
   */
  function createEmptyProgress(slideId = null) {
    return {
      slideId: slideId || null,
      completedTaskIds: [],
      onEnterDoneSlideIds: [],
      completed: false,
      timestamp: Date.now()
    };
  }

  /**
   * @param {any} progress
   * @returns {OnboardingProgress}
   */
  function cloneProgress(progress) {
    const p = progress && typeof progress === 'object' ? progress : {};
    return {
      slideId: typeof p.slideId === 'string' ? p.slideId : null,
      completedTaskIds: Array.isArray(p.completedTaskIds) ? p.completedTaskIds.map(String) : [],
      onEnterDoneSlideIds: Array.isArray(p.onEnterDoneSlideIds) ? p.onEnterDoneSlideIds.map(String) : [],
      completed: !!p.completed,
      timestamp: typeof p.timestamp === 'number' ? p.timestamp : Date.now()
    };
  }

  /**
   * @param {string[]} a
   * @param {string[]} b
   */
  function arraysEqualString(a, b) {
    const aa = Array.isArray(a) ? a : [];
    const bb = Array.isArray(b) ? b : [];
    if (aa.length !== bb.length) return false;
    for (let i = 0; i < aa.length; i++) {
      if (String(aa[i]) !== String(bb[i])) return false;
    }
    return true;
  }

  /**
   * @param {OnboardingProgress|any} a
   * @param {OnboardingProgress|any} b
   */
  function progressEqual(a, b) {
    const aa = cloneProgress(a);
    const bb = cloneProgress(b);
    return (
      aa.slideId === bb.slideId &&
      aa.completed === bb.completed &&
      aa.timestamp === bb.timestamp &&
      arraysEqualString(aa.completedTaskIds, bb.completedTaskIds) &&
      arraysEqualString(aa.onEnterDoneSlideIds, bb.onEnterDoneSlideIds)
    );
  }

  /**
   * @param {{tasks?: Array<{id?: string}>}|null|undefined} slide
   * @param {Set<string>|string[]} completedTaskIds
   */
  function isSlideComplete(slide, completedTaskIds) {
    const tasks = slide?.tasks || [];
    if (!tasks.length) return true;
    const set = completedTaskIds instanceof Set
      ? completedTaskIds
      : new Set(Array.isArray(completedTaskIds) ? completedTaskIds.map(String) : []);
    for (const t of tasks) {
      if (!t?.id) continue;
      if (!set.has(String(t.id))) return false;
    }
    return true;
  }

  // ── Text helpers ────────────────────────────────────────────────────────────

  /**
   * Convert backtick-wrapped segments into <kbd> nodes (no innerHTML).
   * Safer on hostile pages than parsing HTML strings.
   * @param {ParentNode} el
   * @param {string} text
   */
  function renderKeyboardKeysInto(el, text) {
    if (!el) return;
    try { el.textContent = ''; } catch { /* ignore */ }
    const parts = String(text || '').split(/`/);
    for (let i = 0; i < parts.length; i++) {
      const part = parts[i];
      if (!part) continue;
      if (i % 2 === 1) {
        const k = document.createElement('kbd');
        k.textContent = part;
        el.appendChild(k);
      } else {
        el.appendChild(document.createTextNode(part));
      }
    }
  }

  /**
   * @param {string} text
   * @returns {string} HTML with <kbd> (for callers that intentionally use innerHTML)
   */
  function formatKeyboardKeysHtml(text) {
    return String(text || '').replace(/`([^`]+)`/g, '<kbd>$1</kbd>');
  }

  // ── CSS ─────────────────────────────────────────────────────────────────────

  /**
   * @param {{includeViewTransitions?: boolean}} [opts]
   * @returns {string}
   */
  function getOnboardingPanelCss(opts = {}) {
    const includeVt = opts.includeViewTransitions !== false;
    let css =
      `.${ONBOARDING_PANEL_CLASS} kbd {
          font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
          font-size: 11px;
          padding: 1px 6px;
          border: 1px solid #3a3a3a;
          border-bottom-color: #2a2a2a;
          border-radius: 4px;
          background: linear-gradient(180deg, #2b2b2b 0%, #1a1a1a 100%);
          color: #f1f1f1;
        }`;
    if (includeVt) {
      css += `
        @keyframes kpOnboardingSlideOut {
          to { transform: translateX(calc(var(--kp-onboarding-slide-dir, 1) * -100%)); opacity: 0.0; }
        }
        @keyframes kpOnboardingSlideIn {
          from { transform: translateX(calc(var(--kp-onboarding-slide-dir, 1) * 100%)); opacity: 0.0; }
          to { transform: translateX(0%); opacity: 1.0; }
        }
        ::view-transition-old(kp-onboarding-slide-surface) {
          animation: kpOnboardingSlideOut 220ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
        }
        ::view-transition-new(kp-onboarding-slide-surface) {
          animation: kpOnboardingSlideIn 220ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
        }`;
    }
    return css;
  }

  // ── Shell DOM ───────────────────────────────────────────────────────────────

  function assignStyle(el, styles) {
    if (!el || !styles) return;
    try { Object.assign(el.style, styles); } catch { /* ignore */ }
  }

  function mkIconBtn(doc, label, dataAttr, aria) {
    const b = doc.createElement('button');
    b.type = 'button';
    b.textContent = label;
    b.setAttribute(dataAttr, 'true');
    if (aria) b.setAttribute('aria-label', aria);
    assignStyle(b, {
      width: '28px',
      height: '28px',
      borderRadius: '10px',
      border: '1px solid rgba(255,255,255,0.18)',
      background: 'rgba(255,255,255,0.06)',
      color: 'rgba(255,255,255,0.95)',
      cursor: 'pointer',
      fontSize: '14px',
      lineHeight: '26px',
      padding: '0',
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center'
    });
    return b;
  }

  /**
   * Build the floating walkthrough panel shell (header / body / footer).
   * Does not attach event listeners — callers wire close/prev/next/reset.
   *
   * @param {Document} doc
   * @param {Object} [opts]
   * @param {number|string} [opts.zIndex]
   * @param {boolean} [opts.early] Mark as early-inject shell for adoption
   * @param {boolean} [opts.initiallyHidden]
   * @param {boolean} [opts.includeViewTransitions]
   * @param {(el: HTMLElement) => void} [opts.applyTheme]
   * @param {string} [opts.title]
   * @param {string} [opts.stepText]
   * @param {boolean} [opts.navDisabled] Disable prev/next (early shell until wired)
   * @returns {{
   *   root: HTMLElement,
   *   body: HTMLElement,
   *   slideSurface: HTMLElement,
   *   titleEl: HTMLElement,
   *   stepEl: HTMLElement,
   *   prevBtn: HTMLButtonElement,
   *   nextBtn: HTMLButtonElement,
   *   resetBtn: HTMLButtonElement,
   *   closeBtn: HTMLButtonElement
   * }}
   */
  function createOnboardingShell(doc, opts = {}) {
    const zIndex = opts.zIndex != null ? opts.zIndex : ONBOARDING_PANEL_Z_FALLBACK;
    const initiallyHidden = opts.initiallyHidden !== false;
    const includeVt = opts.includeViewTransitions !== false;

    const root = doc.createElement('div');
    root.className = ONBOARDING_PANEL_CLASS;
    root.hidden = initiallyHidden;
    if (opts.early) root.dataset.kpEarlyOnboarding = 'true';
    root.setAttribute('role', 'dialog');
    root.setAttribute('aria-label', 'KeyPilot onboarding walkthrough');

    // When initially hidden, use display:none + pointer-events:none.
    // Some pages override [hidden]; never put display:flex on a hidden shell.
    assignStyle(root, {
      position: 'fixed',
      left: `${ONBOARDING_DEFAULT_LEFT_PX}px`,
      // Prefer sitting below the control strip so the strip is not pushed down.
      top: `${getOnboardingTopBelowControlStrip()}px`,
      width: '360px',
      maxWidth: 'calc(100vw - 24px)',
      maxHeight: 'calc(100vh - 24px)',
      display: initiallyHidden ? 'none' : 'flex',
      flexDirection: 'column',
      overflow: 'hidden',
      zIndex: String(zIndex),
      background: 'rgba(18, 18, 18, 0.94)',
      color: 'rgba(255,255,255,0.95)',
      border: '1px solid rgba(255,255,255,0.12)',
      borderRadius: '14px',
      boxShadow: '0 12px 34px rgba(0,0,0,0.45)',
      fontFamily: 'system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif',
      pointerEvents: initiallyHidden ? 'none' : 'auto'
    });

    try { opts.applyTheme?.(root); } catch { /* ignore */ }

    const style = doc.createElement('style');
    style.textContent = getOnboardingPanelCss({ includeViewTransitions: includeVt });
    root.appendChild(style);

    const header = doc.createElement('div');
    assignStyle(header, {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      gap: '10px',
      padding: '10px 12px',
      borderBottom: '1px solid rgba(255,255,255,0.10)'
    });

    const titleWrap = doc.createElement('div');
    assignStyle(titleWrap, {
      display: 'flex',
      flexDirection: 'column',
      gap: '2px',
      minWidth: '0'
    });

    const titleEl = doc.createElement('div');
    titleEl.textContent = String(opts.title || ONBOARDING_DEFAULT_TITLE);
    titleEl.setAttribute('data-kp-onboarding-title', 'true');
    assignStyle(titleEl, {
      fontSize: '13px',
      fontWeight: '800',
      letterSpacing: '0.2px',
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis'
    });

    const stepEl = doc.createElement('div');
    stepEl.textContent = String(opts.stepText || '1 / 1');
    stepEl.setAttribute('data-kp-onboarding-step', 'true');
    assignStyle(stepEl, {
      fontSize: '12px',
      fontWeight: '600',
      opacity: '0.75'
    });

    // Title wrap only gets the title; step lives in the footer stepWrap
    // (appendChild moves nodes — keep a single step element).
    titleWrap.appendChild(titleEl);

    const navWrap = doc.createElement('div');
    assignStyle(navWrap, {
      display: 'inline-flex',
      alignItems: 'center',
      gap: '8px',
      flex: '0 0 auto'
    });

    const stepWrap = doc.createElement('div');
    assignStyle(stepWrap, {
      display: 'inline-flex',
      alignItems: 'center',
      gap: '6px'
    });

    const prevBtn = mkIconBtn(doc, '←', 'data-kp-onboarding-prev', 'Previous slide');
    const nextBtn = mkIconBtn(doc, '→', 'data-kp-onboarding-next', 'Next slide');
    if (opts.navDisabled) {
      prevBtn.disabled = true;
      nextBtn.disabled = true;
    }

    stepWrap.appendChild(prevBtn);
    stepWrap.appendChild(stepEl);
    stepWrap.appendChild(nextBtn);

    const resetBtn = doc.createElement('button');
    resetBtn.type = 'button';
    resetBtn.textContent = 'Reset';
    resetBtn.setAttribute('data-kp-onboarding-reset', 'true');
    assignStyle(resetBtn, {
      height: '28px',
      borderRadius: '999px',
      border: '1px solid rgba(255,255,255,0.18)',
      background: 'rgba(255,255,255,0.06)',
      color: 'rgba(255,255,255,0.92)',
      cursor: 'pointer',
      fontSize: '12px',
      fontWeight: '700',
      padding: '0 10px',
      lineHeight: '26px'
    });

    const closeBtn = doc.createElement('button');
    closeBtn.type = 'button';
    closeBtn.textContent = '×';
    closeBtn.setAttribute('aria-label', 'Close onboarding walkthrough');
    closeBtn.setAttribute('data-kp-onboarding-close', 'true');
    assignStyle(closeBtn, {
      width: '30px',
      height: '30px',
      borderRadius: '10px',
      border: '1px solid rgba(255,255,255,0.18)',
      background: 'rgba(255,255,255,0.06)',
      color: 'rgba(255,255,255,0.95)',
      cursor: 'pointer',
      fontSize: '18px',
      lineHeight: '28px',
      padding: '0',
      flex: '0 0 auto'
    });

    navWrap.appendChild(closeBtn);
    header.appendChild(titleWrap);
    header.appendChild(navWrap);

    const body = doc.createElement('div');
    body.setAttribute('data-kp-onboarding-body', 'true');
    assignStyle(body, {
      flex: '1',
      overflowY: 'auto',
      minHeight: '0',
      position: 'relative'
    });

    const slideSurface = doc.createElement('div');
    slideSurface.setAttribute('data-kp-onboarding-slide-surface', 'true');
    assignStyle(slideSurface, { padding: '12px' });
    body.appendChild(slideSurface);

    const footer = doc.createElement('div');
    assignStyle(footer, {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      gap: '10px',
      padding: '10px 12px',
      borderTop: '1px solid rgba(255,255,255,0.10)'
    });
    footer.appendChild(stepWrap);
    footer.appendChild(resetBtn);

    root.appendChild(header);
    root.appendChild(body);
    root.appendChild(footer);

    return {
      root,
      body,
      slideSurface,
      titleEl,
      stepEl,
      prevBtn,
      nextBtn,
      resetBtn,
      closeBtn
    };
  }

  /**
   * Query shell refs from an existing panel root (early-inject adoption).
   * @param {Element|null} root
   */
  function queryOnboardingShellRefs(root) {
    if (!root) return null;
    const body =
      root.querySelector('[data-kp-onboarding-body="true"]') ||
      root.querySelector(':scope > div[data-kp-onboarding-body]');
    if (!body) return null;
    let slideSurface = body.querySelector('[data-kp-onboarding-slide-surface="true"]');
    if (!slideSurface) {
      slideSurface = document.createElement('div');
      slideSurface.setAttribute('data-kp-onboarding-slide-surface', 'true');
      assignStyle(slideSurface, { padding: '12px' });
      try { body.appendChild(slideSurface); } catch { /* ignore */ }
    }
    return {
      root,
      body,
      slideSurface,
      titleEl: root.querySelector('[data-kp-onboarding-title="true"]'),
      stepEl: root.querySelector('[data-kp-onboarding-step="true"]'),
      prevBtn: root.querySelector('button[data-kp-onboarding-prev="true"]'),
      nextBtn: root.querySelector('button[data-kp-onboarding-next="true"]'),
      resetBtn: root.querySelector('button[data-kp-onboarding-reset="true"]'),
      closeBtn: root.querySelector('button[data-kp-onboarding-close="true"]')
    };
  }

  /**
   * Show/hide panel in a way that survives hostile [hidden] CSS overrides.
   * @param {HTMLElement|null} root
   * @param {boolean} visible
   */
  function setOnboardingPanelVisible(root, visible) {
    if (!root) return;
    const show = !!visible;
    try {
      root.hidden = !show;
      root.style.display = show ? 'flex' : 'none';
      root.style.pointerEvents = show ? 'auto' : 'none';
      if (show) positionOnboardingBelowControlStrip(root);
    } catch { /* ignore */ }
  }

  // ── Slide content ───────────────────────────────────────────────────────────

  function applyTaskRowInteractive(row, { uncheckable, onTaskRowClick }) {
    if (!row) return;
    try {
      if (uncheckable) {
        row.setAttribute('data-kp-onboarding-uncheckable', 'true');
        row.style.cursor = 'pointer';
        row.title = 'Click to uncheck (undo last completed step)';
        row.setAttribute('role', 'button');
        row.tabIndex = 0;
      } else {
        row.removeAttribute('data-kp-onboarding-uncheckable');
        row.style.cursor = '';
        row.removeAttribute('title');
        row.removeAttribute('role');
        row.removeAttribute('tabindex');
      }
    } catch { /* ignore */ }

    try {
      if (row._kpOnboardingTaskClick) {
        row.removeEventListener('click', row._kpOnboardingTaskClick);
        row._kpOnboardingTaskClick = null;
      }
    } catch { /* ignore */ }
    if (uncheckable && typeof onTaskRowClick === 'function') {
      row._kpOnboardingTaskClick = onTaskRowClick;
      try { row.addEventListener('click', onTaskRowClick); } catch { /* ignore */ }
    }
  }

  function applyTaskRowVisual(row, task, done, opts = {}) {
    if (!row) return;
    assignStyle(row, {
      background: done ? 'rgba(46, 204, 113, 0.10)' : 'rgba(255,255,255,0.04)'
    });

    const box =
      row.querySelector(':scope > div[aria-hidden="true"]') ||
      row.firstElementChild;
    const textEl =
      (box && box.nextElementSibling) ||
      row.querySelector(':scope > div:last-child');

    if (box) {
      assignStyle(box, {
        border: done ? '1px solid rgba(46, 204, 113, 0.9)' : '1px solid rgba(255,255,255,0.22)',
        background: done ? 'rgba(46, 204, 113, 0.85)' : 'transparent',
        boxShadow: done ? '0 0 0 2px rgba(46, 204, 113, 0.18)' : 'none'
      });
      try {
        const existingCheck = box.querySelector(':scope > div');
        if (done) {
          if (!existingCheck) {
            const check = document.createElement('div');
            check.textContent = '✓';
            assignStyle(check, {
              position: 'absolute',
              inset: '0',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '13px',
              fontWeight: '800',
              color: '#0b1410'
            });
            box.appendChild(check);
          }
        } else if (existingCheck) {
          box.removeChild(existingCheck);
        }
      } catch { /* ignore */ }
    }

    if (textEl) {
      try {
        renderKeyboardKeysInto(textEl, task.label || task.id);
        assignStyle(textEl, {
          color: done ? 'rgba(255,255,255,0.92)' : 'rgba(255,255,255,0.88)',
          opacity: done ? '0.95' : '1'
        });
      } catch { /* ignore */ }
    }

    applyTaskRowInteractive(row, {
      uncheckable: !!(done && opts.uncheckable),
      onTaskRowClick: opts.onTaskRowClick
    });
  }

  function createTaskRow(doc, task, done, opts = {}) {
    const row = doc.createElement('div');
    row.setAttribute('data-kp-onboarding-task-id', task.id);
    assignStyle(row, {
      display: 'flex',
      alignItems: 'flex-start',
      gap: '10px',
      padding: '8px 10px',
      borderRadius: '10px',
      border: '1px solid rgba(255,255,255,0.10)',
      background: done ? 'rgba(46, 204, 113, 0.10)' : 'rgba(255,255,255,0.04)'
    });

    const box = doc.createElement('div');
    box.setAttribute('aria-hidden', 'true');
    assignStyle(box, {
      width: '18px',
      height: '18px',
      borderRadius: '6px',
      border: done ? '1px solid rgba(46, 204, 113, 0.9)' : '1px solid rgba(255,255,255,0.22)',
      background: done ? 'rgba(46, 204, 113, 0.85)' : 'transparent',
      boxShadow: done ? '0 0 0 2px rgba(46, 204, 113, 0.18)' : 'none',
      flex: '0 0 auto',
      marginTop: '1px',
      position: 'relative'
    });

    if (done) {
      const check = doc.createElement('div');
      check.textContent = '✓';
      assignStyle(check, {
        position: 'absolute',
        inset: '0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontSize: '13px',
        fontWeight: '800',
        color: '#0b1410'
      });
      box.appendChild(check);
    }

    const text = doc.createElement('div');
    renderKeyboardKeysInto(text, task.label || task.id);
    assignStyle(text, {
      fontSize: '13px',
      lineHeight: '1.35',
      color: done ? 'rgba(255,255,255,0.92)' : 'rgba(255,255,255,0.88)',
      opacity: done ? '0.95' : '1'
    });

    row.appendChild(box);
    row.appendChild(text);
    applyTaskRowInteractive(row, {
      uncheckable: !!(done && opts.uncheckable),
      onTaskRowClick: opts.onTaskRowClick
    });
    return row;
  }

  /**
   * Render or update slide checklist into the slide surface.
   *
   * @param {HTMLElement} surface
   * @param {Object} params
   * @param {Array<{id:string, label?:string}>} [params.tasks]
   * @param {Set<string>|string[]} [params.completedTaskIds]
   * @param {string|null} [params.lastCompletedTaskId]
   * @param {(e:Event)=>void} [params.onTaskRowClick]
   * @param {string} [params.bodyText]
   * @param {boolean} [params.forceRebuild]
   * @param {boolean} [params.showTip]
   * @param {Document} [params.doc]
   */
  function renderOnboardingSlideSurface(surface, params = {}) {
    if (!surface) return;
    const doc = params.doc || surface.ownerDocument || document;
    const tasks = (params.tasks || []).filter((t) => t && t.id);
    const completedSet = params.completedTaskIds instanceof Set
      ? params.completedTaskIds
      : new Set(Array.isArray(params.completedTaskIds) ? params.completedTaskIds.map(String) : []);
    const lastCompletedTaskId = params.lastCompletedTaskId != null ? String(params.lastCompletedTaskId) : '';
    const onTaskRowClick = typeof params.onTaskRowClick === 'function' ? params.onTaskRowClick : null;
    const bodyTextStr = String(params.bodyText || '').trim();
    const forceRebuild = !!params.forceRebuild;
    const showTip = params.showTip !== false;

    const existingRows = surface.querySelectorAll('[data-kp-onboarding-task-id]');
    const existingBody = surface.querySelector('[data-kp-onboarding-body-text="true"]');

    const canUpdateInPlace =
      !forceRebuild &&
      existingRows.length === tasks.length &&
      tasks.every((t, i) => existingRows[i]?.getAttribute('data-kp-onboarding-task-id') === t.id);

    // Body text (independent of task update mode when possible)
    try {
      if (bodyTextStr) {
        if (existingBody && canUpdateInPlace) {
          existingBody.textContent = '';
          // Preserve line breaks without full HTML parse
          const lines = bodyTextStr.split('\n');
          lines.forEach((line, i) => {
            if (i > 0) existingBody.appendChild(doc.createElement('br'));
            renderKeyboardKeysInto(
              (() => { const s = doc.createElement('span'); existingBody.appendChild(s); return s; })(),
              line
            );
          });
          existingBody.style.display = 'block';
          existingBody.style.marginBottom = tasks.length ? '12px' : '0px';
        }
      } else if (existingBody && canUpdateInPlace) {
        existingBody.style.display = 'none';
        existingBody.textContent = '';
      }
    } catch { /* ignore */ }

    if (canUpdateInPlace) {
      tasks.forEach((task, i) => {
        const done = completedSet.has(task.id);
        applyTaskRowVisual(existingRows[i], task, done, {
          uncheckable: done && task.id === lastCompletedTaskId,
          onTaskRowClick
        });
      });
      return;
    }

    // Full rebuild
    while (surface.firstChild) surface.removeChild(surface.firstChild);

    if (bodyTextStr) {
      const body = doc.createElement('div');
      body.setAttribute('data-kp-onboarding-body-text', 'true');
      const lines = bodyTextStr.split('\n');
      lines.forEach((line, i) => {
        if (i > 0) body.appendChild(doc.createElement('br'));
        const span = doc.createElement('span');
        renderKeyboardKeysInto(span, line);
        body.appendChild(span);
      });
      assignStyle(body, {
        fontSize: '13px',
        lineHeight: '1.45',
        color: 'rgba(255,255,255,0.90)',
        marginBottom: tasks.length ? '12px' : '0px',
        opacity: '0.95'
      });
      surface.appendChild(body);
    }

    const list = doc.createElement('div');
    assignStyle(list, {
      display: 'flex',
      flexDirection: 'column',
      gap: '8px'
    });

    for (const task of tasks) {
      const done = completedSet.has(task.id);
      list.appendChild(createTaskRow(doc, task, done, {
        uncheckable: done && task.id === lastCompletedTaskId,
        onTaskRowClick
      }));
    }
    surface.appendChild(list);

    if (showTip) {
      const tip = doc.createElement('div');
      tip.setAttribute('data-kp-onboarding-tip', 'true');
      tip.textContent = ONBOARDING_REOPEN_TIP;
      assignStyle(tip, {
        marginTop: '10px',
        fontSize: '12px',
        opacity: '0.78',
        lineHeight: '1.35',
        color: 'rgba(255,255,255,0.85)'
      });
      surface.appendChild(tip);
    }
  }

  /**
   * Update chrome (title, step counter, nav disabled state).
   * @param {Object} refs
   * @param {Object} params
   */
  function updateOnboardingChrome(refs, params = {}) {
    if (!refs) return;
    const idx = Number(params.slideIndex) || 0;
    const total = Math.max(1, Number(params.slideCount) || 1);
    try {
      if (refs.titleEl) refs.titleEl.textContent = String(params.title || ONBOARDING_DEFAULT_TITLE);
    } catch { /* ignore */ }
    try {
      if (refs.stepEl) refs.stepEl.textContent = `${idx + 1} / ${total}`;
    } catch { /* ignore */ }
    try {
      if (refs.root && params.slideId != null) {
        refs.root.dataset.kpOnboardingSlideId = String(params.slideId || '');
      }
    } catch { /* ignore */ }
    try {
      if (refs.prevBtn) refs.prevBtn.disabled = idx <= 0;
    } catch { /* ignore */ }
    try {
      if (refs.nextBtn) refs.nextBtn.disabled = idx >= total - 1;
    } catch { /* ignore */ }
  }

  // ── Overlay ─────────────────────────────────────────────────────────────────

  /**
   * Ensure modal overlay exists inside the scrollable body host.
   * @param {HTMLElement} bodyHost
   * @param {Document} [doc]
   * @returns {{
   *   overlayEl: HTMLElement,
   *   titleEl: HTMLElement,
   *   msgEl: HTMLElement,
   *   primaryBtn: HTMLButtonElement,
   *   secondaryBtn: HTMLButtonElement
   * }|null}
   */
  function ensureOnboardingOverlay(bodyHost, doc) {
    if (!bodyHost) return null;
    const d = doc || bodyHost.ownerDocument || document;

    const existing = bodyHost.querySelector('[data-kp-onboarding-overlay="true"]');
    if (existing) {
      return {
        overlayEl: existing,
        titleEl: existing.querySelector('[data-kp-onboarding-overlay-title="true"]'),
        msgEl: existing.querySelector('[data-kp-onboarding-overlay-message="true"]'),
        primaryBtn: existing.querySelector('button[data-kp-onboarding-overlay-primary="true"]'),
        secondaryBtn: existing.querySelector('button[data-kp-onboarding-overlay-secondary="true"]')
      };
    }

    const overlay = d.createElement('div');
    overlay.setAttribute('data-kp-onboarding-overlay', 'true');
    overlay.hidden = true;
    assignStyle(overlay, {
      position: 'absolute',
      inset: '0',
      padding: '14px',
      display: 'none',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'rgba(0,0,0,0.42)',
      backdropFilter: 'blur(10px)',
      WebkitBackdropFilter: 'blur(10px)',
      zIndex: '5',
      pointerEvents: 'none'
    });

    const card = d.createElement('div');
    assignStyle(card, {
      width: '100%',
      maxWidth: '320px',
      borderRadius: '14px',
      border: '1px solid rgba(255,255,255,0.16)',
      background: 'rgba(18, 18, 18, 0.78)',
      boxShadow: '0 16px 44px rgba(0,0,0,0.55)',
      padding: '14px 14px 12px 14px'
    });

    const titleEl = d.createElement('div');
    titleEl.setAttribute('data-kp-onboarding-overlay-title', 'true');
    titleEl.textContent = 'Nice!';
    assignStyle(titleEl, {
      fontSize: '14px',
      fontWeight: '900',
      letterSpacing: '0.2px',
      marginBottom: '8px'
    });

    const msgEl = d.createElement('div');
    msgEl.setAttribute('data-kp-onboarding-overlay-message', 'true');
    msgEl.textContent = '';
    assignStyle(msgEl, {
      fontSize: '13px',
      lineHeight: '1.35',
      color: 'rgba(255,255,255,0.90)',
      whiteSpace: 'pre-wrap'
    });

    const btnRow = d.createElement('div');
    assignStyle(btnRow, {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'flex-end',
      gap: '8px',
      marginTop: '12px'
    });

    const mkBtn = (variant) => {
      const b = d.createElement('button');
      b.type = 'button';
      assignStyle(b, {
        height: '30px',
        borderRadius: '999px',
        border: variant === 'primary' ? '1px solid rgba(46, 204, 113, 0.55)' : '1px solid rgba(255,255,255,0.20)',
        background: variant === 'primary' ? 'rgba(46, 204, 113, 0.18)' : 'rgba(255,255,255,0.06)',
        color: 'rgba(255,255,255,0.92)',
        cursor: 'pointer',
        fontSize: '12px',
        fontWeight: '800',
        padding: '0 12px',
        lineHeight: '28px'
      });
      return b;
    };

    const secondaryBtn = mkBtn('secondary');
    secondaryBtn.hidden = true;
    secondaryBtn.textContent = '';
    secondaryBtn.setAttribute('data-kp-onboarding-overlay-secondary', 'true');

    const primaryBtn = mkBtn('primary');
    primaryBtn.textContent = 'OK';
    primaryBtn.setAttribute('data-kp-onboarding-overlay-primary', 'true');

    btnRow.appendChild(secondaryBtn);
    btnRow.appendChild(primaryBtn);
    card.appendChild(titleEl);
    card.appendChild(msgEl);
    card.appendChild(btnRow);
    overlay.appendChild(card);
    bodyHost.appendChild(overlay);

    return { overlayEl: overlay, titleEl, msgEl, primaryBtn, secondaryBtn };
  }

  /**
   * @param {HTMLElement|null} overlayEl
   * @param {boolean} open
   * @param {HTMLElement|null} [root]
   */
  function setOnboardingOverlayOpen(overlayEl, open, root = null) {
    if (!overlayEl) return;
    try {
      overlayEl.hidden = !open;
      overlayEl.style.display = open ? 'flex' : 'none';
      overlayEl.style.pointerEvents = open ? 'auto' : 'none';
      if (root) {
        if (open) root.dataset.kpOnboardingOverlayOpen = 'true';
        else delete root.dataset.kpOnboardingOverlayOpen;
      }
    } catch { /* ignore */ }
  }

  // --- end stamped onboarding-shared.js ---
// KP_EARLY_INJECT_UI_END

  // Essential CSS for early injection - no longer needed for cursor element
  // Important: we intentionally mirror the main extension's cursor CSS contract:
  // - When `html` has `kpv2-cursor-hidden`, we force the cursor via `--kpv2-cursor`.
  // This prevents the "cursor pop-in" that used to happen at document_idle.
  // Keep print rules in sync with buildKeyPilotPrintCss() in style-manager.js.
  // Early shells (control strip, keyboard ref, onboarding) can exist before #kpv2-style.
  const EARLY_CSS = `
    /* KeyPilot early cursor (document_start) */
    html.${CURSOR_HIDDEN_CLASS} * {
      cursor: var(${CURSOR_VAR}, auto) !important;
    }

    /* Ensure cursor overrides work on common interactive elements */
    html.${CURSOR_HIDDEN_CLASS} a[href],
    html.${CURSOR_HIDDEN_CLASS} button,
    html.${CURSOR_HIDDEN_CLASS} input,
    html.${CURSOR_HIDDEN_CLASS} select,
    html.${CURSOR_HIDDEN_CLASS} textarea,
    html.${CURSOR_HIDDEN_CLASS} [role="button"],
    html.${CURSOR_HIDDEN_CLASS} [role="link"],
    html.${CURSOR_HIDDEN_CLASS} [onclick],
    html.${CURSOR_HIDDEN_CLASS} [tabindex] {
      cursor: var(${CURSOR_VAR}, auto) !important;
    }

    /* Hide KeyPilot early chrome when printing / saving as PDF. */
    @media print {
      .kp-control-strip,
      .kp-floating-keyboard-help,
      .kp-onboarding-panel,
      [data-kp-control-strip],
      [data-kp-early-control-strip],
      [data-kp-early-floating-keyboard] {
        display: none !important;
        visibility: hidden !important;
      }
    }

    /*
     * Hostile host pages (e.g. Zapier) override UA [hidden]{display:none}.
     * Keep closed keyboard shells invisible even when only the attribute is set.
     * Shown state still uses inline display:flex !important from JS.
     */
    .kp-floating-keyboard-help[hidden],
    .kp-floating-keyboard-help.kpv2-hidden,
    .kp-floating-keyboard-help[aria-hidden="true"] {
      display: none !important;
      pointer-events: none !important;
    }
  `;

  // Early cursor state
  let isExtensionEnabled = true;
  let currentMode = 'none';
  let mousePosition = { x: 0, y: 0 };
  let earlyObserver = null;
  let earlyClickableElements = new Set();
  let keyboardListenersActive = false;
  let pendingKeyEvents = [];
  let cursorApplied = false; // Track if cursor has been applied to prevent unnecessary updates
  let cursorSettingsChanged = false; // Track if settings changed to force cursor reapplication
  let isMainExtensionLoaded = false; // Track if main extension has taken over
  let keyboardHelpVisible = false;
  let keyboardLayoutId = (typeof DEFAULT_KEYBOARD_LAYOUT_ID === 'string' && DEFAULT_KEYBOARD_LAYOUT_ID)
    ? DEFAULT_KEYBOARD_LAYOUT_ID
    : 'browsing-right';
  let keyboardHelpRoot = null;
  let keyboardHelpKeyboardContainer = null;
  let keyboardHelpStorageListener = null;
  let onboardingRoot = null;
  let onboardingStorageListener = null;
  // Control strip defaults match SettingsManager DEFAULT_SETTINGS.controlStrip
  let controlStripRoot = null;
  let controlStripDesiredVisible = true;
  let controlStripCollapsed = true;
  let controlStripStorageListener = null;
  let controlStripRefs = null; // { statusBtn, statusDot, statusLabel, modules, moveBtn, keyboardBtn, settingsBtn, collapseBtn, closeBtn }
  let mainLoadedListenerInstalled = false;

  function setupMainLoadedHandoffListener() {
    if (mainLoadedListenerInstalled) return;
    mainLoadedListenerInstalled = true;

    // Clean up when main extension loads - early-inject must yield control.
    // (This used to be wired from the cursor takeover path, but the cursor is now CSS-based,
    // so we listen unconditionally.)
    window.addEventListener('keypilot-main-loaded', () => {
      isMainExtensionLoaded = true;

      // Stop early mouse tracking (main extension will handle this)
      try { document.removeEventListener('mousemove', handleMouseMove); } catch {}

      // Stop early keyboard capture
      try { stopEarlyKeyboardCapture(); } catch {}

      // Stop early DOM observation
      try {
        if (earlyObserver) {
          earlyObserver.disconnect();
          earlyObserver = null;
        }
      } catch {}

      // Stop reacting to storage changes once the main extension is active
      try {
        if (keyboardHelpStorageListener && chrome?.storage?.onChanged) {
          chrome.storage.onChanged.removeListener(keyboardHelpStorageListener);
        }
      } catch {}
      keyboardHelpStorageListener = null;

      try {
        if (cursorSettingsListener && chrome?.storage?.onChanged) {
          chrome.storage.onChanged.removeListener(cursorSettingsListener);
        }
      } catch {}
      cursorSettingsListener = null;

      // Stop reacting to onboarding storage changes once the main extension is active.
      // We keep the onboarding DOM in place so the bundled script can adopt it.
      try {
        if (onboardingStorageListener && chrome?.storage?.onChanged) {
          chrome.storage.onChanged.removeListener(onboardingStorageListener);
        }
      } catch {}
      onboardingStorageListener = null;

      // Stop reacting to control-strip settings once the main extension is active.
      // Keep the DOM so ControlStrip can adopt it without flicker.
      try {
        if (controlStripStorageListener && chrome?.storage?.onChanged) {
          chrome.storage.onChanged.removeListener(controlStripStorageListener);
        }
      } catch {}
      controlStripStorageListener = null;

      console.log('[KeyPilot Early] Handed off to main extension, cursor control yielded');
    }, { once: true });
  }

  /**
   * Build (or adopt) the early walkthrough shell.
   * Shell DOM comes from stamped onboarding-shared.js (createOnboardingShell).
   */
  function ensureOnboardingShell() {
    try {
      if (window !== window.top) return null;
      if (onboardingRoot && onboardingRoot.isConnected) return onboardingRoot;

      const existing = document.querySelector('.kp-onboarding-panel[data-kp-early-onboarding="true"]');
      if (existing && existing.isConnected) {
        onboardingRoot = existing;
        return onboardingRoot;
      }

      if (typeof createOnboardingShell !== 'function') return null;

      const shell = createOnboardingShell(document, {
        zIndex: Z_ONBOARDING_PANEL,
        early: true,
        initiallyHidden: true,
        includeViewTransitions: false,
        applyTheme: typeof applyPopupThemeVars === 'function' ? applyPopupThemeVars : null,
        stepText: '…',
        navDisabled: true
      });

      const { root, slideSurface, titleEl, stepEl, resetBtn, closeBtn } = shell;

      // Early-inject reset: clear progress + re-enable onboarding (dual-write).
      resetBtn.addEventListener('click', () => {
        try {
          const firstId =
            (typeof ONBOARDING_FIRST_SLIDE_ID === 'string' && ONBOARDING_FIRST_SLIDE_ID) ||
            'basic_navigation';
          const progress =
            typeof createEmptyProgress === 'function'
              ? createEmptyProgress(firstId)
              : {
                  slideId: firstId,
                  completedTaskIds: [],
                  onEnterDoneSlideIds: [],
                  completed: false,
                  timestamp: Date.now()
                };
          const activeKey =
            (typeof ONBOARDING_STORAGE_KEYS !== 'undefined' && ONBOARDING_STORAGE_KEYS.ACTIVE) ||
            ONBOARDING_ACTIVE_STORAGE_KEY;
          const progressKey =
            (typeof ONBOARDING_STORAGE_KEYS !== 'undefined' && ONBOARDING_STORAGE_KEYS.PROGRESS) ||
            ONBOARDING_PROGRESS_STORAGE_KEY;
          const payload = {
            [activeKey]: true,
            [progressKey]: progress
          };
          const writeBoth = async () => {
            try { await chrome.storage.sync.set(payload); } catch { /* ignore */ }
            try { await chrome.storage.local.set(payload); } catch { /* ignore */ }
          };
          writeBoth()
            .then(() => {
              if (isMainExtensionLoaded) return;
              try {
                if (typeof setOnboardingPanelVisible === 'function') {
                  setOnboardingPanelVisible(root, true);
                } else {
                  root.hidden = false;
                  root.style.display = 'flex';
                  root.style.pointerEvents = 'auto';
                }
                renderEarlyOnboardingContent(
                  { body: slideSurface, titleEl, stepEl },
                  progress
                );
              } catch { /* ignore */ }
            })
            .catch(() => {});
        } catch { /* ignore */ }
      });

      // Closing in early-inject should persist so the panel doesn't return on next page.
      closeBtn.addEventListener('click', () => {
        try {
          if (typeof setOnboardingPanelVisible === 'function') {
            setOnboardingPanelVisible(root, false);
          } else {
            root.hidden = true;
            root.style.display = 'none';
            root.style.pointerEvents = 'none';
          }
        } catch { /* ignore */ }
        try {
          const activeKey =
            (typeof ONBOARDING_STORAGE_KEYS !== 'undefined' && ONBOARDING_STORAGE_KEYS.ACTIVE) ||
            ONBOARDING_ACTIVE_STORAGE_KEY;
          const payload = { [activeKey]: false, timestamp: Date.now() };
          const writeBoth = async () => {
            try { await chrome.storage.sync.set(payload); } catch { /* ignore */ }
            try { await chrome.storage.local.set(payload); } catch { /* ignore */ }
          };
          writeBoth().catch(() => {});
        } catch { /* ignore */ }
      });

      // Best-effort initial checklist (storage-backed render updates shortly after).
      try {
        const firstId =
          (typeof ONBOARDING_FIRST_SLIDE_ID === 'string' && ONBOARDING_FIRST_SLIDE_ID) ||
          'basic_navigation';
        renderEarlyOnboardingContent(
          { body: slideSurface, titleEl, stepEl },
          { slideId: firstId, completedTaskIds: [] }
        );
      } catch { /* ignore */ }

      (document.body || document.documentElement).appendChild(root);
      onboardingRoot = root;
      return onboardingRoot;
    } catch {
      return null;
    }
  }

  function getEarlyOnboardingModel() {
    try {
      if (typeof EARLY_ONBOARDING_MODEL === 'object' && EARLY_ONBOARDING_MODEL && Array.isArray(EARLY_ONBOARDING_MODEL.slides)) {
        return EARLY_ONBOARDING_MODEL;
      }
    } catch { /* ignore */ }
    return { slides: [] };
  }

  function findEarlySlide(model, slideId) {
    const slides = model && Array.isArray(model.slides) ? model.slides : [];
    const id = String(slideId || '').trim();
    if (id) {
      const found = slides.find((s) => s && String(s.id || '').trim() === id);
      if (found) return found;
    }
    return slides[0] || null;
  }

  function renderEarlyOnboardingContent(refs, progress) {
    // Thin wrapper over stamped onboarding-shared helpers so early checklist
    // DOM matches the bundled OnboardingPanel (seamless adoption).
    const model = getEarlyOnboardingModel();
    const slide = findEarlySlide(model, progress && progress.slideId);
    if (!slide) return;

    const slides = model.slides || [];
    const slideIndex = Math.max(0, slides.findIndex((s) => s && s.id === slide.id));
    const slideCount = Math.max(1, slides.length || 1);
    const completed = Array.isArray(progress?.completedTaskIds)
      ? progress.completedTaskIds.map(String)
      : [];

    const surface =
      refs?.body ||
      onboardingRoot?.querySelector?.('[data-kp-onboarding-slide-surface="true"]') ||
      onboardingRoot?.querySelector?.('[data-kp-onboarding-body="true"]');
    const titleEl = refs?.titleEl || onboardingRoot?.querySelector?.('[data-kp-onboarding-title="true"]');
    const stepEl = refs?.stepEl || onboardingRoot?.querySelector?.('[data-kp-onboarding-step="true"]');
    if (!surface) return;

    const chromeRefs = { root: onboardingRoot, titleEl, stepEl };
    if (typeof updateOnboardingChrome === 'function') {
      updateOnboardingChrome(chromeRefs, {
        title: slide.title || (typeof ONBOARDING_DEFAULT_TITLE === 'string' ? ONBOARDING_DEFAULT_TITLE : 'Welcome to KeyPilot'),
        slideId: slide.id,
        slideIndex,
        slideCount
      });
    } else {
      try {
        if (titleEl) titleEl.textContent = String(slide.title || 'Welcome to KeyPilot');
        if (stepEl) stepEl.textContent = `${slideIndex + 1} / ${slideCount}`;
      } catch { /* ignore */ }
    }

    if (typeof renderOnboardingSlideSurface === 'function') {
      renderOnboardingSlideSurface(surface, {
        tasks: slide.tasks || [],
        completedTaskIds: completed,
        bodyText: slide.bodyText || '',
        forceRebuild: true,
        // Match bundled onboarding-manager: hide tip on practice/scrolling/tabs/completion.
        showTip: slide.id !== 'text_box_mode' &&
          slide.id !== 'scrolling' &&
          slide.id !== 'tabs' &&
          slide.id !== 'completion'
      });
    }
  }

  async function readOnboardingState() {
    // returns: { active: boolean|null, completed: boolean|null, slideId: string|null, completedTaskIds: string[] }
    // Merge sync + local per-key (prefer newer progress by timestamp, else sync).
    const result = { active: null, completed: null, slideId: null, completedTaskIds: [] };
    let syncObj = null;
    let localObj = null;

    try {
      syncObj = await chrome.storage.sync.get([ONBOARDING_ACTIVE_STORAGE_KEY, ONBOARDING_PROGRESS_STORAGE_KEY]);
    } catch { /* ignore */ }
    try {
      localObj = await chrome.storage.local.get([ONBOARDING_ACTIVE_STORAGE_KEY, ONBOARDING_PROGRESS_STORAGE_KEY]);
    } catch { /* ignore */ }

    try {
      const syncActive = syncObj && typeof syncObj[ONBOARDING_ACTIVE_STORAGE_KEY] === 'boolean'
        ? syncObj[ONBOARDING_ACTIVE_STORAGE_KEY]
        : null;
      const localActive = localObj && typeof localObj[ONBOARDING_ACTIVE_STORAGE_KEY] === 'boolean'
        ? localObj[ONBOARDING_ACTIVE_STORAGE_KEY]
        : null;
      if (syncActive !== null) result.active = syncActive;
      else if (localActive !== null) result.active = localActive;

      const syncProg = syncObj && syncObj[ONBOARDING_PROGRESS_STORAGE_KEY];
      const localProg = localObj && localObj[ONBOARDING_PROGRESS_STORAGE_KEY];
      const syncTs = syncProg && typeof syncProg === 'object' && typeof syncProg.timestamp === 'number' ? syncProg.timestamp : 0;
      const localTs = localProg && typeof localProg === 'object' && typeof localProg.timestamp === 'number' ? localProg.timestamp : 0;

      let prog = null;
      if (syncProg && typeof syncProg === 'object' && localProg && typeof localProg === 'object') {
        prog = localTs > syncTs ? localProg : syncProg;
      } else if (syncProg && typeof syncProg === 'object') {
        prog = syncProg;
      } else if (localProg && typeof localProg === 'object') {
        prog = localProg;
      }

      if (prog) {
        if (typeof prog.completed === 'boolean') result.completed = prog.completed;
        if (typeof prog.slideId === 'string') result.slideId = prog.slideId;
        if (Array.isArray(prog.completedTaskIds)) result.completedTaskIds = prog.completedTaskIds.map(String);
      }
    } catch { /* ignore */ }

    return result;
  }

  async function readEnabledState() {
    // returns: { enabled: boolean|null }
    const result = { enabled: null };
    const KEY = 'keypilot_enabled';
    const parse = (obj) => {
      try {
        if (!obj || typeof obj !== 'object') return;
        if (typeof obj[KEY] === 'boolean') result.enabled = obj[KEY];
      } catch { /* ignore */ }
    };

    try {
      const sync = await chrome.storage.sync.get([KEY]);
      parse(sync);
      if (result.enabled !== null) return result;
    } catch { /* ignore */ }

    try {
      const local = await chrome.storage.local.get([KEY]);
      parse(local);
    } catch { /* ignore */ }

    return result;
  }

  async function refreshEarlyOnboardingVisibility() {
    try {
      if (isMainExtensionLoaded) return;
      if (window !== window.top) return;
      const root = ensureOnboardingShell();
      if (!root) return;

      const state = await readOnboardingState();
      const enabledState = await readEnabledState();
      // Conservative default: if we can't confirm enabled, do not show.
      // This matches the bundled onboarding behavior and prevents load-time flashes.
      const isEnabled = enabledState.enabled === true;
      const shouldShow = isEnabled && state.active === true && state.completed !== true;
      if (typeof setOnboardingPanelVisible === 'function') {
        setOnboardingPanelVisible(root, shouldShow);
      } else {
        root.hidden = !shouldShow;
        root.style.display = shouldShow ? 'flex' : 'none';
        root.style.pointerEvents = shouldShow ? 'auto' : 'none';
      }
      if (shouldShow) {
        // Keep the early checklist in sync so the main bundled UI can adopt without a visual "pop".
        try { renderEarlyOnboardingContent(null, state); } catch { /* ignore */ }
      }
      // Control strip sits below onboarding when both occupy the top-left.
      try { syncEarlyControlStripOnboardingOffset(); } catch { /* ignore */ }
    } catch {
      // ignore
    }
  }

  function setupEarlyOnboardingStorageSync() {
    try {
      if (window !== window.top) return;
      ensureOnboardingShell();
      refreshEarlyOnboardingVisibility(); // async

      if (!chrome?.storage?.onChanged?.addListener) return;
      if (onboardingStorageListener) return;

      onboardingStorageListener = (changes, area) => {
        try {
          if (isMainExtensionLoaded) return;
          if (area !== 'sync' && area !== 'local') return;
          if (!changes) return;
          if (!changes[ONBOARDING_ACTIVE_STORAGE_KEY] && !changes[ONBOARDING_PROGRESS_STORAGE_KEY] && !changes['keypilot_enabled']) return;
          refreshEarlyOnboardingVisibility(); // async
        } catch { /* ignore */ }
      };

      chrome.storage.onChanged.addListener(onboardingStorageListener);
    } catch {
      // ignore
    }
  }

  function ensureKeybindingsUiStylesInjected(doc) {
    try {
      if (!doc || !doc.head) return;
      if (doc.head.querySelector(`style[${KEYBINDINGS_UI_STYLE_ATTR}]`)) return;
      const style = doc.createElement('style');
      style.setAttribute(KEYBINDINGS_UI_STYLE_ATTR, 'true');
      // Replace build-time font placeholders with runtime extension URLs (required on real web pages).
      let css = KEYBINDINGS_UI_EARLY_CSS;
      try {
        const getURL = chrome && chrome.runtime && chrome.runtime.getURL ? chrome.runtime.getURL.bind(chrome.runtime) : null;
        if (getURL) {
          css = css
            .replaceAll('__KP_FONT_ROBOTECH_URL__', getURL('fonts/ROBOTECHGPRegular.ttf'))
            .replaceAll('__KP_FONT_TITILLIUM_URL__', getURL('fonts/TitilliumTextRegular.otf'))
            .replaceAll('__KP_FONT_CUBELLAN_URL__', getURL('fonts/CubellanRegular.ttf'))
            .replaceAll('__KP_FONT_EZARION_URL__', getURL('fonts/EzarionRegular.ttf'))
            .replaceAll('__KP_FONT_DOSIS_URL__', getURL('fonts/DosisBook.ttf'));
        }
      } catch {
        // ignore; fallback to placeholders (bundled UI will overwrite later)
      }
      style.textContent = css;
      doc.head.appendChild(style);
    } catch {
      // ignore
    }
  }

  function el(doc, tag, className, text) {
    const node = doc.createElement(tag);
    if (className) node.className = className;
    if (text !== undefined) node.textContent = text;
    return node;
  }

  function normalizeKeyboardLayoutId(raw) {
    const v = String(raw || '').trim();
    if (v === 'browsing-left') return 'browsing-left';
    return 'browsing-right';
  }

  function getEarlyKeyboardDataForLayout(layoutId) {
    const id = normalizeKeyboardLayoutId(layoutId);
    try {
      const layout = (typeof KEYBOARD_LAYOUTS_BY_ID === 'object' && KEYBOARD_LAYOUTS_BY_ID && KEYBOARD_LAYOUTS_BY_ID[id])
        ? KEYBOARD_LAYOUTS_BY_ID[id]
        : KEYBINDINGS_KEYBOARD_LAYOUT;
      const bindings = (typeof EARLY_KEYBINDINGS_BY_ID === 'object' && EARLY_KEYBINDINGS_BY_ID && EARLY_KEYBINDINGS_BY_ID[id])
        ? EARLY_KEYBINDINGS_BY_ID[id]
        : EARLY_KEYBINDINGS;
      return { id, layout, bindings };
    } catch {
      return { id: DEFAULT_KEYBOARD_LAYOUT_ID || 'browsing-right', layout: KEYBINDINGS_KEYBOARD_LAYOUT, bindings: EARLY_KEYBINDINGS };
    }
  }

  function renderEarlyKeyboard(container, { layoutId } = {}) {
    if (!container) return;
    const doc = container.ownerDocument || document;
    ensureKeybindingsUiStylesInjected(doc);

    // If already rendered, don't redo work.
    let existing = null;
    try { existing = container.querySelector(':scope > .keyboard-visual'); } catch { /* ignore */ }
    if (!existing) {
      try { existing = container.querySelector('.keyboard-visual'); } catch { /* ignore */ }
    }
    if (existing && existing.dataset && existing.dataset.kpKeyboardBuilt === 'true') {
      const existingLayoutId = String(existing.dataset.kpLayoutId || '');
      const desired = normalizeKeyboardLayoutId(layoutId || DEFAULT_KEYBOARD_LAYOUT_ID);
      if (!existingLayoutId || existingLayoutId === desired) return;
      // Layout changed: re-render so key positions update (prevents right->left mismatch).
    }

    container.textContent = '';
    const visual = el(doc, 'div', 'keyboard-visual kp-keybindings-ui');
    visual.dataset.kpKeyboardBuilt = 'true';
    try {
      const desired = normalizeKeyboardLayoutId(layoutId || DEFAULT_KEYBOARD_LAYOUT_ID);
      visual.dataset.kpLayoutId = desired;
    } catch { /* ignore */ }
    container.appendChild(visual);

    const data = getEarlyKeyboardDataForLayout(layoutId || DEFAULT_KEYBOARD_LAYOUT_ID);
    const layout = data.layout || KEYBINDINGS_KEYBOARD_LAYOUT;
    const bindings = data.bindings || EARLY_KEYBINDINGS;

    for (const row of layout) {
      const rowEl = el(doc, 'div', 'keyboard-row');
      visual.appendChild(rowEl);

      for (const item of row) {
        const ensureBgIcon = (keyEl) => {
          try {
            if (keyEl.querySelector(':scope > .key-bg-icon')) return;
          } catch {
            if (keyEl.querySelector('.key-bg-icon')) return;
          }
          const icon = doc.createElement('span');
          icon.className = 'key-bg-icon';
          icon.setAttribute('aria-hidden', 'true');
          keyEl.insertBefore(icon, keyEl.firstChild);
        };

        const ensurePressOverlay = (keyEl) => {
          try {
            if (keyEl.querySelector(':scope > .key-press-overlay')) return;
          } catch {
            if (keyEl.querySelector('.key-press-overlay')) return;
          }
          const overlay = doc.createElement('span');
          overlay.className = 'key-press-overlay';
          overlay.setAttribute('aria-hidden', 'true');
          keyEl.appendChild(overlay);
        };

        if (item.type === 'special') {
          // No KeyPilot function → no background icon.
          const keyEl = el(doc, 'div', item.className || 'key');
          keyEl.appendChild(el(doc, 'span', 'key-text', item.text));
          ensurePressOverlay(keyEl);
          rowEl.appendChild(keyEl);
          continue;
        }
        if (item.type === 'key') {
          // Unassigned alphanumeric key → no background icon.
          const keyEl = el(doc, 'div', 'key');
          keyEl.appendChild(el(doc, 'span', 'key-text', item.text));
          ensurePressOverlay(keyEl);
          rowEl.appendChild(keyEl);
          continue;
        }

        const binding = bindings[item.id];
        const baseClass = item.className || 'key';
        const className = `${baseClass}${binding && binding.keyboardClass ? ' ' + binding.keyboardClass : ''}`;
        const keyEl = el(doc, 'div', className);
        keyEl.dataset.kpActionId = item.id;
        keyEl.dataset.kpBaseClass = baseClass;
        keyEl.setAttribute('role', 'button');
        keyEl.setAttribute('tabindex', '0');
        // Prefer aria-label over title so the browser native tooltip doesn't fight our hover popover.
        try { keyEl.removeAttribute('title'); } catch { /* ignore */ }
        keyEl.setAttribute(
          'aria-label',
          (binding && (binding.description || binding.label)) || item.fallbackText || item.id
        );
        // Only keys with functions get FA background icons.
        ensureBgIcon(keyEl);

        const main = el(doc, 'div', 'key-main', (binding && binding.label) || item.fallbackText || item.id);
        keyEl.appendChild(main);

        const labelText = (binding && (binding.displayKey || binding.keyLabel)) || '';
        if (labelText) {
          keyEl.appendChild(el(doc, 'div', 'key-label', labelText));
        }

        ensurePressOverlay(keyEl);
        rowEl.appendChild(keyEl);
      }
    }
  }

  /**
   * Generate SVG data URI for cursor
   */
  function getCursorDataUri(options = {}) {
    // Extract parameters with defaults
    const {
      crossHairQuadrantWidth = 15,
      gap = 0,
      strokeLineCap = 'round',
      strokeWidth = 4,
      crossHairScalingFactor = 1
    } = options;

    // Apply scaling factor
    const scaledGap = gap * crossHairScalingFactor;
    const scaledWidth = crossHairQuadrantWidth * crossHairScalingFactor;

    // Calculate segment positions (center is now at 30,30 for 60x60 canvas)
    const centerX = 30;
    const centerY = 30;
    
    let segmentStart, segmentEnd, segmentStart2, segmentEnd2;
    
    if (scaledGap === 0) {
      // Intersecting lines: bars extend from center outward
      segmentStart = centerY - scaledWidth;
      segmentEnd = centerY;
      segmentStart2 = centerY;
      segmentEnd2 = centerY + scaledWidth;
    } else {
      // Four separate bars: each bar is `gap` pixels away from center
      segmentStart = centerY - scaledGap - scaledWidth;
      segmentEnd = centerY - scaledGap;
      segmentStart2 = centerY + scaledGap;
      segmentEnd2 = centerY + scaledGap + scaledWidth;
    }

    const color = FOCUS_GREEN_BRIGHT;
    const svgContent = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 60" width="60" height="60">
      <line x1="30" y1="${segmentStart}" x2="30" y2="${segmentEnd}" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="${strokeLineCap}"/>
      <line x1="30" y1="${segmentStart2}" x2="30" y2="${segmentEnd2}" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="${strokeLineCap}"/>
      <line x1="${segmentStart}" y1="30" x2="${segmentEnd}" y2="30" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="${strokeLineCap}"/>
      <line x1="${segmentStart2}" y1="30" x2="${segmentEnd2}" y2="30" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="${strokeLineCap}"/>
    </svg>`;
    const encoded = encodeURIComponent(svgContent);
    return `data:image/svg+xml,${encoded}`;
  }

  /**
   * Get cursor settings from storage
   */
  async function getCursorSettings() {
    const defaultSettings = {
      cursorMode: CURSOR_MODE.NO_CUSTOM_CURSORS,
      type: 'crosshair',
      lineWidth: 4,
      sizePixels: 10,
      gap: 6
    };

    try {
      // Try sync storage first
      const syncResult = await chrome.storage.sync.get([SETTINGS_STORAGE_KEY]);
      const stored = syncResult?.[SETTINGS_STORAGE_KEY];
      
      if (stored && typeof stored === 'object') {
        const cursorMode = stored.cursorMode === CURSOR_MODE.CUSTOM_CURSORS || stored.cursorMode === CURSOR_MODE.NO_CUSTOM_CURSORS
          ? stored.cursorMode
          : defaultSettings.cursorMode;

        const cursor = (stored.clickMode && stored.clickMode.cursor && typeof stored.clickMode.cursor === 'object')
          ? stored.clickMode.cursor
          : {};
        // Check if gap is missing or if it's the old default (0) with old sizePixels default (15)
        // This handles fresh installs and migration from old defaults
        const hasOldDefaults = cursor.gap === 0 && cursor.sizePixels === 15;
        const gapValue = (typeof cursor.gap === 'number' && cursor.gap !== null && !hasOldDefaults) 
          ? cursor.gap 
          : defaultSettings.gap;
        const sizePixelsValue = (typeof cursor.sizePixels === 'number' && cursor.sizePixels !== null && !hasOldDefaults)
          ? cursor.sizePixels
          : defaultSettings.sizePixels;
        
        return {
          cursorMode,
          type: cursor.type || defaultSettings.type,
          lineWidth: typeof cursor.lineWidth === 'number' ? cursor.lineWidth : defaultSettings.lineWidth,
          sizePixels: sizePixelsValue,
          gap: gapValue
        };
      }
    } catch (syncError) {
      // Fallback to local storage
      try {
        const localResult = await chrome.storage.local.get([SETTINGS_STORAGE_KEY]);
        const stored = localResult?.[SETTINGS_STORAGE_KEY];
        
        if (stored && typeof stored === 'object') {
          const cursorMode = stored.cursorMode === CURSOR_MODE.CUSTOM_CURSORS || stored.cursorMode === CURSOR_MODE.NO_CUSTOM_CURSORS
            ? stored.cursorMode
            : defaultSettings.cursorMode;

          const cursor = (stored.clickMode && stored.clickMode.cursor && typeof stored.clickMode.cursor === 'object')
            ? stored.clickMode.cursor
            : {};
          // Check if gap is missing or if it's the old default (0) with old sizePixels default (15)
          // This handles fresh installs and migration from old defaults
          const hasOldDefaults = cursor.gap === 0 && cursor.sizePixels === 15;
          const gapValue = (typeof cursor.gap === 'number' && cursor.gap !== null && !hasOldDefaults) 
            ? cursor.gap 
            : defaultSettings.gap;
          const sizePixelsValue = (typeof cursor.sizePixels === 'number' && cursor.sizePixels !== null && !hasOldDefaults)
            ? cursor.sizePixels
            : defaultSettings.sizePixels;
          
          return {
            cursorMode,
            type: cursor.type || defaultSettings.type,
            lineWidth: typeof cursor.lineWidth === 'number' ? cursor.lineWidth : defaultSettings.lineWidth,
            sizePixels: sizePixelsValue,
            gap: gapValue
          };
        }
      } catch (localError) {
        // Ignore
      }
    }
    
    return defaultSettings;
  }

  /**
   * Apply CSS cursor for early injection
   */
  async function applyEarlyCursor() {
    // Only apply once to prevent flickering (unless settings changed)
    if (cursorApplied && !cursorSettingsChanged) {
      return;
    }

    const settings = await getCursorSettings();
    cursorSettingsChanged = false;

    // Cursor mode disabled: do not override the page cursor at all.
    if (settings.cursorMode !== CURSOR_MODE.CUSTOM_CURSORS) {
      try {
        if (document.documentElement) {
          document.documentElement.classList.remove(CURSOR_HIDDEN_CLASS);
          document.documentElement.style.removeProperty(CURSOR_VAR);
          document.documentElement.style.cursor = '';
        }
        if (document.body) {
          document.body.style.cursor = '';
        }
      } catch {}
      cursorApplied = true;
      return;
    }

    // Handle native cursor types
    if (settings.type === 'native_arrow') {
      try {
        if (document.documentElement) {
          document.documentElement.style.setProperty(CURSOR_VAR, 'default');
          document.documentElement.classList.add(CURSOR_HIDDEN_CLASS);
        }
      } catch {}
      cursorApplied = true;
      return;
    }

    if (settings.type === 'native_pointer') {
      try {
        if (document.documentElement) {
          document.documentElement.style.setProperty(CURSOR_VAR, 'pointer');
          document.documentElement.classList.add(CURSOR_HIDDEN_CLASS);
        }
      } catch {}
      cursorApplied = true;
      return;
    }

    // Use settings to generate cursor
    const cursorUri = getCursorDataUri({
      crossHairQuadrantWidth: settings.sizePixels,
      gap: settings.gap,
      strokeWidth: settings.lineWidth,
      crossHairScalingFactor: 1
    });
    const cursorValue = `url("${cursorUri}") 30 30, auto`;

    // Mirror main extension behavior: set the CSS variable + class.
    // This makes the cursor apply across all elements via the injected CSS above.
    try {
      if (document.documentElement) {
        document.documentElement.style.setProperty(CURSOR_VAR, cursorValue);
        document.documentElement.classList.add(CURSOR_HIDDEN_CLASS);
      }
    } catch {}

    cursorApplied = true;
  }

  /**
   * Update cursor position (not needed for CSS cursor, but kept for compatibility)
   */
  function updateCursorPosition(x, y) {
    mousePosition = { x, y };
  }

  /**
   * Show/hide cursor based on extension state
   */
  async function updateCursorVisibility() {
    // If main extension has loaded, it's in charge of the cursor
    if (isMainExtensionLoaded) {
      return;
    }

    if (isExtensionEnabled) {
      await applyEarlyCursor();
    } else {
      // Reset cursor applied flag when disabling
      cursorApplied = false;
      try {
        if (document.documentElement) {
          document.documentElement.classList.remove(CURSOR_HIDDEN_CLASS);
          document.documentElement.style.removeProperty(CURSOR_VAR);
          document.documentElement.style.cursor = 'default';
        }
        if (document.body) {
          document.body.style.cursor = 'default';
        }
      } catch {}
    }
  }

  /**
   * Merge a partial controlStrip object into kp_settings_v1 (sync, then local fallback).
   * @param {{ visible?: boolean, collapsed?: boolean }} partial
   */
  function persistEarlyControlStripSettings(partial) {
    try {
      if (!chrome?.storage) return;
      const apply = (area) => {
        area.get([SETTINGS_STORAGE_KEY], (result) => {
          try {
            if (chrome.runtime?.lastError) return;
            const prev = result && result[SETTINGS_STORAGE_KEY] && typeof result[SETTINGS_STORAGE_KEY] === 'object'
              ? result[SETTINGS_STORAGE_KEY]
              : {};
            const prevCs = prev.controlStrip && typeof prev.controlStrip === 'object' ? prev.controlStrip : {};
            const next = {
              ...prev,
              controlStrip: {
                visible: typeof partial.visible === 'boolean' ? partial.visible : (prevCs.visible !== false),
                collapsed: typeof partial.collapsed === 'boolean' ? partial.collapsed : !!prevCs.collapsed
              }
            };
            area.set({ [SETTINGS_STORAGE_KEY]: next }, () => {
              try { void chrome.runtime?.lastError; } catch { /* ignore */ }
            });
          } catch { /* ignore */ }
        });
      };
      apply(chrome.storage.sync);
      // Also write local as a best-effort mirror (SettingsManager reads sync first).
      try { apply(chrome.storage.local); } catch { /* ignore */ }
    } catch { /* ignore */ }
  }

  function parseControlStripFromSettings(settingsObj) {
    const cs = settingsObj && typeof settingsObj === 'object' && settingsObj.controlStrip
      && typeof settingsObj.controlStrip === 'object'
      ? settingsObj.controlStrip
      : null;
    return {
      // Defaults match SettingsManager DEFAULT_SETTINGS.controlStrip
      visible: cs ? cs.visible !== false : true,
      collapsed: cs ? !!cs.collapsed : true
    };
  }

  function createEarlyControlStripSegmentButton(opts) {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.setAttribute('aria-label', opts.ariaLabel || '');
    if (opts.title) btn.title = opts.title;
    if (opts.text) {
      const label = document.createElement('span');
      label.textContent = opts.text;
      Object.assign(label.style, {
        pointerEvents: 'none',
        lineHeight: '1'
      });
      btn.appendChild(label);
    }
    Object.assign(btn.style, {
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      gap: '4px',
      height: '100%',
      minHeight: `${CONTROL_STRIP_HEIGHT_PX - 2}px`,
      margin: '0',
      padding: opts.compact ? '0 8px' : '0 10px',
      border: 'none',
      borderRight: opts.last ? 'none' : '1px solid rgba(255,255,255,0.08)',
      borderRadius: '0',
      background: opts.primary
        ? 'linear-gradient(180deg, #1a1b1f 0%, #121316 100%)'
        : 'transparent',
      color: 'rgba(220, 220, 225, 0.92)',
      fontSize: '11px',
      fontWeight: '600',
      letterSpacing: '0.01em',
      lineHeight: '1',
      cursor: 'pointer',
      flex: '0 0 auto',
      boxShadow: 'none',
      outline: 'none',
      whiteSpace: 'nowrap'
    });
    btn.addEventListener('mouseenter', () => {
      try {
        if (isMainExtensionLoaded) return;
        if (btn === controlStripRefs?.keyboardBtn && keyboardHelpVisible) {
          btn.style.background = 'rgba(59, 130, 246, 0.18)';
        } else {
          btn.style.background = opts.primary
            ? 'linear-gradient(180deg, #22232a 0%, #18191e 100%)'
            : 'rgba(255,255,255,0.06)';
        }
      } catch { /* ignore */ }
    });
    btn.addEventListener('mouseleave', () => {
      try {
        if (isMainExtensionLoaded) return;
        if (btn === controlStripRefs?.keyboardBtn && keyboardHelpVisible) {
          btn.style.background = 'rgba(59, 130, 246, 0.18)';
        } else {
          btn.style.background = opts.primary
            ? 'linear-gradient(180deg, #1a1b1f 0%, #121316 100%)'
            : 'transparent';
        }
      } catch { /* ignore */ }
    });
    return btn;
  }

  function renderEarlyControlStripStatus() {
    const refs = controlStripRefs;
    if (!refs || !refs.statusLabel || !refs.statusDot) return;
    const on = !!isExtensionEnabled;
    try {
      refs.statusLabel.textContent = on ? 'ON' : 'OFF';
      refs.statusDot.style.background = on
        ? 'rgba(16, 185, 129, 0.95)'
        : 'rgba(148, 163, 184, 0.85)';
      refs.statusDot.style.boxShadow = on
        ? '0 0 0 2px rgba(16, 185, 129, 0.2)'
        : '0 0 0 2px rgba(148, 163, 184, 0.15)';
      refs.statusLabel.style.color = on
        ? 'rgba(167, 243, 208, 0.95)'
        : 'rgba(148, 163, 184, 0.95)';
      if (refs.statusBtn) {
        refs.statusBtn.setAttribute('aria-pressed', on ? 'true' : 'false');
        refs.statusBtn.title = on
          ? 'KeyPilot is on — click to turn off (Alt+K)'
          : 'KeyPilot is off — click to turn on (Alt+K)';
      }
    } catch { /* ignore */ }
  }

  function renderEarlyControlStripKeyboard() {
    const btn = controlStripRefs?.keyboardBtn;
    if (!btn) return;
    const active = !!keyboardHelpVisible && !!isExtensionEnabled;
    try {
      btn.setAttribute('aria-pressed', active ? 'true' : 'false');
      btn.style.background = active ? 'rgba(59, 130, 246, 0.18)' : 'transparent';
      btn.style.color = active
        ? 'rgba(191, 219, 254, 0.98)'
        : 'rgba(220, 220, 225, 0.92)';
      btn.title = active ? 'Hide keyboard reference' : 'Show keyboard reference';
    } catch { /* ignore */ }
  }

  function applyEarlyControlStripCollapsedLayout() {
    const refs = controlStripRefs;
    if (!controlStripRoot || !refs) return;
    const collapsed = !!controlStripCollapsed;
    try {
      if (refs.modules) refs.modules.style.display = collapsed ? 'none' : 'flex';
      if (refs.closeBtn) refs.closeBtn.style.display = collapsed ? 'none' : 'inline-flex';
      if (refs.collapseBtn) {
        refs.collapseBtn.textContent = collapsed ? '▶' : '◀';
        refs.collapseBtn.setAttribute(
          'aria-label',
          collapsed ? 'Expand control strip' : 'Collapse control strip'
        );
        refs.collapseBtn.title = collapsed ? 'Expand' : 'Collapse';
        refs.collapseBtn.style.borderRight = collapsed
          ? 'none'
          : '1px solid rgba(255,255,255,0.08)';
      }
      controlStripRoot.setAttribute('data-kp-collapsed', collapsed ? 'true' : 'false');
    } catch { /* ignore */ }
  }

  function syncEarlyControlStripOnboardingOffset() {
    // Walkthrough sits relative to the strip; do not force strip back to top-left
    // (user position is restored from settings when available).
    if (!controlStripRoot || !controlStripRoot.isConnected) return;
    try {
      const panel = document.querySelector('.kp-onboarding-panel');
      if (!panel || !panel.isConnected) return;
      const hidden = panel.hidden === true
        || panel.getAttribute('hidden') !== null
        || panel.style.display === 'none'
        || (window.getComputedStyle
          && (window.getComputedStyle(panel).display === 'none'
            || window.getComputedStyle(panel).visibility === 'hidden'));
      if (hidden) return;
      if (typeof positionOnboardingBelowControlStrip === 'function') {
        positionOnboardingBelowControlStrip(panel);
        return;
      }
      // Fallback before shared helpers are stamped/available.
      const rect = controlStripRoot.getBoundingClientRect();
      const top = Math.max(
        CONTROL_STRIP_DEFAULT_TOP_PX,
        Math.round((rect && rect.bottom ? rect.bottom : (CONTROL_STRIP_DEFAULT_TOP_PX + CONTROL_STRIP_HEIGHT_PX))
          + CONTROL_STRIP_ONBOARDING_GAP_PX)
      );
      panel.style.top = `${top}px`;
    } catch { /* ignore */ }
  }

  /**
   * Lightweight dock helpers (mirrors utils/panel-position.js for document_start).
   * Full drag/snap lives in the bundled content script.
   */
  const EARLY_PANEL_MARGIN_PX = 16;
  const EARLY_STRIP_MARGIN_PX = 16;

  function earlyViewportSize() {
    try {
      const de = document.documentElement;
      // client* can be 0 at document_start — prefer the larger of client/inner.
      return {
        width: Math.max(0, de?.clientWidth || 0, window.innerWidth || 0),
        height: Math.max(0, de?.clientHeight || 0, window.innerHeight || 0)
      };
    } catch {
      return {
        width: Math.max(0, window.innerWidth || 0),
        height: Math.max(0, window.innerHeight || 0)
      };
    }
  }

  function earlyReapplyKeyboardPosition() {
    if (isMainExtensionLoaded) return;
    if (!keyboardHelpRoot || !keyboardHelpRoot.isConnected) return;
    try {
      earlyApplyPanelPosition(keyboardHelpRoot, earlyPanelPositions && earlyPanelPositions.keyboardReference, {
        margin: EARLY_PANEL_MARGIN_PX,
        defaultAnchor: 'bottom-left',
        defaultWidth: 760,
        defaultHeight: 200
      });
    } catch { /* ignore */ }
  }

  // Reclamp after first layout / resize so early positions aren't stuck at vh=0 defaults.
  try {
    window.addEventListener('resize', earlyReapplyKeyboardPosition, true);
    window.addEventListener('load', earlyReapplyKeyboardPosition, true);
  } catch { /* ignore */ }

  function earlyClampPanelPosition(left, top, width, height, margin) {
    const m = Math.max(0, Number(margin) || 0);
    const vp = earlyViewportSize();
    const vw = vp.width;
    const vh = vp.height;
    const w = Math.max(0, Number(width) || 0);
    const h = Math.max(0, Number(height) || 0);
    const maxLeft = Math.max(m, vw - w - m);
    const maxTop = Math.max(m, vh - h - m);
    return {
      left: Math.max(m, Math.min(Number(left) || m, maxLeft)),
      top: Math.max(m, Math.min(Number(top) || m, maxTop))
    };
  }

  function earlyPositionForAnchor(anchor, width, height, margin) {
    const m = Math.max(0, Number(margin) || 0);
    const vp = earlyViewportSize();
    const vw = vp.width;
    const vh = vp.height;
    const w = Math.max(0, Number(width) || 0);
    const h = Math.max(0, Number(height) || 0);
    const leftMin = m;
    const topMin = m;
    const leftMax = Math.max(m, vw - w - m);
    const topMax = Math.max(m, vh - h - m);
    const leftCenter = Math.round((vw - w) / 2);
    const topCenter = Math.round((vh - h) / 2);
    let left = leftMin;
    let top = topMin;
    switch (String(anchor || '')) {
      case 'top-left': left = leftMin; top = topMin; break;
      case 'top-center': left = leftCenter; top = topMin; break;
      case 'top-right': left = leftMax; top = topMin; break;
      case 'middle-left': left = leftMin; top = topCenter; break;
      case 'middle-right': left = leftMax; top = topCenter; break;
      case 'bottom-left': left = leftMin; top = topMax; break;
      case 'bottom-center': left = leftCenter; top = topMax; break;
      case 'bottom-right': left = leftMax; top = topMax; break;
      default: left = leftMin; top = topMin; break;
    }
    return earlyClampPanelPosition(left, top, w, h, m);
  }

  /**
   * @param {HTMLElement|null} el
   * @param {{ left?: number, top?: number, anchor?: string|null }|null|undefined} stored
   * @param {{ margin?: number, defaultAnchor?: string, defaultWidth?: number, defaultHeight?: number }} opts
   */
  function earlyApplyPanelPosition(el, stored, opts) {
    if (!el || !el.style) return;
    const margin = opts && Number.isFinite(opts.margin) ? opts.margin : EARLY_PANEL_MARGIN_PX;
    const defaultAnchor = (opts && opts.defaultAnchor) || 'top-left';
    const rect = el.getBoundingClientRect();
    // Never clamp with 0 height — that docks free tops at vh−margin; content then grows off-screen.
    let width = (rect && rect.width) || (opts && opts.defaultWidth) || 0;
    let height = (rect && rect.height) || (opts && opts.defaultHeight) || 0;
    if (width < 32) width = (opts && opts.defaultWidth) || 760;
    if (height < 32) height = (opts && opts.defaultHeight) || 200;
    const state = stored && typeof stored === 'object' ? stored : null;
    let next;
    if (state && typeof state.anchor === 'string' && state.anchor) {
      next = earlyPositionForAnchor(state.anchor, width, height, margin);
    } else if (state && Number.isFinite(Number(state.left)) && Number.isFinite(Number(state.top))) {
      next = earlyClampPanelPosition(Number(state.left), Number(state.top), width, height, margin);
    } else {
      next = earlyPositionForAnchor(defaultAnchor, width, height, margin);
    }
    try {
      el.style.position = 'fixed';
      el.style.right = 'auto';
      el.style.bottom = 'auto';
      el.style.left = `${Math.round(next.left)}px`;
      el.style.top = `${Math.round(next.top)}px`;
      el.style.margin = '0';
    } catch { /* ignore */ }

    // Remeasure after paint-sized content and reclamp (keyboard often sizes after shell create).
    try {
      const live = el.getBoundingClientRect();
      const lw = live.width || width;
      const lh = live.height || height;
      if (lw >= 32 && lh >= 32) {
        let next2;
        if (state && typeof state.anchor === 'string' && state.anchor) {
          next2 = earlyPositionForAnchor(state.anchor, lw, lh, margin);
        } else if (state && Number.isFinite(Number(state.left)) && Number.isFinite(Number(state.top))) {
          next2 = earlyClampPanelPosition(Number(state.left), Number(state.top), lw, lh, margin);
        } else {
          next2 = earlyPositionForAnchor(defaultAnchor, lw, lh, margin);
        }
        // Also pin if painted box still spills the viewport.
        const spills =
          live.bottom > earlyViewportSize().height - margin + 1 ||
          live.top < margin - 1 ||
          live.right > earlyViewportSize().width - margin + 1 ||
          live.left < margin - 1;
        if (spills) {
          next2 = earlyClampPanelPosition(live.left, live.top, lw, lh, margin);
        } else if (
          Math.abs(next2.left - next.left) > 0.5 ||
          Math.abs(next2.top - next.top) > 0.5
        ) {
          // use next2
        } else {
          next2 = next;
        }
        el.style.left = `${Math.round(next2.left)}px`;
        el.style.top = `${Math.round(next2.top)}px`;
      }
    } catch { /* ignore */ }
  }

  /** Cached panelPositions from kp_settings_v1 (best-effort at document_start). */
  let earlyPanelPositions = null;

  function readEarlyPanelPositionsFromSettingsObj(settingsObj) {
    try {
      const pp = settingsObj && typeof settingsObj === 'object' && settingsObj.panelPositions
        && typeof settingsObj.panelPositions === 'object'
        ? settingsObj.panelPositions
        : null;
      if (!pp) return null;
      return {
        keyboardReference: pp.keyboardReference && typeof pp.keyboardReference === 'object'
          ? pp.keyboardReference
          : null,
        controlStrip: pp.controlStrip && typeof pp.controlStrip === 'object'
          ? pp.controlStrip
          : null
      };
    } catch {
      return null;
    }
  }

  /**
   * Ensure the control strip shell exists early (document_start).
   * The bundled ControlStrip will adopt this element later to avoid flicker.
   */
  function ensureEarlyControlStripShell() {
    try {
      if (window !== window.top) return null;
      if (isMainExtensionLoaded) return controlStripRoot;
      if (controlStripRoot && controlStripRoot.isConnected) return controlStripRoot;

      const existing = document.querySelector('.kp-control-strip[data-kp-early-control-strip="true"]');
      if (existing && existing.isConnected) {
        controlStripRoot = existing;
        const modulesEl = existing.querySelector('[data-kp-control-strip-modules="true"]');
        let moveBtn = existing.querySelector('[data-kp-control-strip-move="true"]');
        // Older early shells (or a race before this segment existed) may lack move.
        if (modulesEl && !moveBtn) {
          try {
            moveBtn = createEarlyControlStripSegmentButton({
              ariaLabel: 'Move control strip',
              title: 'Drag to move',
              text: '⠿',
              compact: true
            });
            moveBtn.setAttribute('data-kp-control-strip-move', 'true');
            try {
              moveBtn.style.cursor = 'grab';
              moveBtn.style.touchAction = 'none';
              moveBtn.style.letterSpacing = '0';
              moveBtn.style.fontSize = '12px';
              moveBtn.style.opacity = '0.85';
            } catch { /* ignore */ }
            moveBtn.addEventListener('click', (e) => {
              try { e.preventDefault(); e.stopPropagation(); } catch { /* ignore */ }
            });
            modulesEl.insertBefore(moveBtn, modulesEl.firstChild);
          } catch { /* ignore */ }
        }
        controlStripRefs = {
          statusBtn: existing.querySelector('[data-kp-control-strip-status="true"]'),
          statusDot: existing.querySelector('[data-kp-control-strip-status-dot="true"]'),
          statusLabel: existing.querySelector('[data-kp-control-strip-status-label="true"]'),
          modules: modulesEl,
          moveBtn: existing.querySelector('[data-kp-control-strip-move="true"]'),
          keyboardBtn: existing.querySelector('[data-kp-control-strip-keyboard="true"]'),
          settingsBtn: existing.querySelector('[data-kp-control-strip-settings="true"]'),
          collapseBtn: existing.querySelector('[data-kp-control-strip-collapse="true"]'),
          closeBtn: existing.querySelector('[data-kp-control-strip-close="true"]')
        };
        return controlStripRoot;
      }

      const root = document.createElement('div');
      root.className = 'kp-control-strip';
      root.hidden = true;
      root.setAttribute('role', 'toolbar');
      root.setAttribute('aria-label', 'KeyPilot control strip');
      root.setAttribute('data-kp-control-strip', 'true');
      root.setAttribute('data-kp-early-control-strip', 'true');
      root.dataset.kpEarlyControlStrip = 'true';

      Object.assign(root.style, {
        position: 'fixed',
        left: `${CONTROL_STRIP_DEFAULT_LEFT_PX}px`,
        top: `${CONTROL_STRIP_DEFAULT_TOP_PX}px`,
        height: `${CONTROL_STRIP_HEIGHT_PX}px`,
        minHeight: `${CONTROL_STRIP_HEIGHT_PX}px`,
        maxHeight: `${CONTROL_STRIP_HEIGHT_PX}px`,
        // Stay fully hidden until applyEarlyControlStripVisibility decides.
        display: 'none',
        flexDirection: 'row',
        alignItems: 'stretch',
        zIndex: String(Z_CONTROL_STRIP),
        background: 'rgba(10, 11, 14, 0.98)',
        color: 'rgba(248, 250, 252, 0.95)',
        // Match onboarding panel rim (light gray outline).
        border: '1px solid rgba(255,255,255,0.12)',
        borderRadius: '4px',
        boxShadow: '0 8px 24px rgba(0,0,0,0.5), 0 1px 4px rgba(0,0,0,0.35)',
        fontFamily: 'system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif',
        pointerEvents: 'none',
        overflow: 'hidden',
        boxSizing: 'border-box',
        userSelect: 'none',
        WebkitUserSelect: 'none'
      });
      try { applyPopupThemeVars(root); } catch { /* ignore */ }
      try {
        earlyApplyPanelPosition(root, earlyPanelPositions && earlyPanelPositions.controlStrip, {
          margin: EARLY_STRIP_MARGIN_PX,
          defaultAnchor: 'top-left',
          defaultHeight: CONTROL_STRIP_HEIGHT_PX
        });
      } catch { /* ignore */ }

      const statusBtn = createEarlyControlStripSegmentButton({
        ariaLabel: 'Toggle KeyPilot on or off',
        title: 'Toggle KeyPilot (Alt+K)',
        primary: true
      });
      statusBtn.setAttribute('data-kp-control-strip-status', 'true');

      const statusInner = document.createElement('span');
      Object.assign(statusInner.style, {
        display: 'inline-flex',
        alignItems: 'center',
        gap: '6px',
        pointerEvents: 'none'
      });

      const statusDot = document.createElement('span');
      Object.assign(statusDot.style, {
        width: '7px',
        height: '7px',
        borderRadius: '50%',
        flex: '0 0 auto',
        background: 'rgba(16, 185, 129, 0.95)',
        boxShadow: '0 0 0 2px rgba(16, 185, 129, 0.2)'
      });
      statusDot.setAttribute('aria-hidden', 'true');
      statusDot.setAttribute('data-kp-control-strip-status-dot', 'true');

      const statusLabel = document.createElement('span');
      statusLabel.textContent = 'ON';
      statusLabel.setAttribute('data-kp-control-strip-status-label', 'true');
      Object.assign(statusLabel.style, {
        fontSize: '11px',
        fontWeight: '700',
        letterSpacing: '0.06em',
        lineHeight: '1'
      });

      statusInner.appendChild(statusDot);
      statusInner.appendChild(statusLabel);
      statusBtn.appendChild(statusInner);

      const modules = document.createElement('div');
      modules.setAttribute('data-kp-control-strip-modules', 'true');
      Object.assign(modules.style, {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'stretch',
        flex: '0 0 auto'
      });

      // Drag grip (expanded only). Full drag/snap is bound by the main ControlStrip
      // after handoff; include the segment here so the shell matches post-handoff layout.
      const moveBtn = createEarlyControlStripSegmentButton({
        ariaLabel: 'Move control strip',
        title: 'Drag to move',
        text: '⠿',
        compact: true
      });
      moveBtn.setAttribute('data-kp-control-strip-move', 'true');
      try {
        moveBtn.style.cursor = 'grab';
        moveBtn.style.touchAction = 'none';
        moveBtn.style.letterSpacing = '0';
        moveBtn.style.fontSize = '12px';
        moveBtn.style.opacity = '0.85';
      } catch { /* ignore */ }
      moveBtn.addEventListener('click', (e) => {
        try { e.preventDefault(); e.stopPropagation(); } catch { /* ignore */ }
      });

      const keyboardBtn = createEarlyControlStripSegmentButton({
        ariaLabel: 'Toggle keyboard reference',
        title: 'Keyboard reference',
        text: 'KB'
      });
      keyboardBtn.setAttribute('data-kp-control-strip-keyboard', 'true');

      const settingsBtn = createEarlyControlStripSegmentButton({
        ariaLabel: 'Open KeyPilot settings',
        title: 'Settings',
        text: 'Settings'
      });
      settingsBtn.setAttribute('data-kp-control-strip-settings', 'true');

      modules.appendChild(moveBtn);
      modules.appendChild(keyboardBtn);
      modules.appendChild(settingsBtn);

      const collapseBtn = createEarlyControlStripSegmentButton({
        ariaLabel: 'Collapse control strip',
        title: 'Collapse',
        text: '◀',
        compact: true
      });
      collapseBtn.setAttribute('data-kp-control-strip-collapse', 'true');

      const closeBtn = createEarlyControlStripSegmentButton({
        ariaLabel: 'Close control strip',
        title: 'Close (Alt+J to show again)',
        text: '×',
        compact: true,
        last: true
      });
      closeBtn.setAttribute('data-kp-control-strip-close', 'true');

      // Early interactions (guarded so main extension owns handlers after handoff).
      statusBtn.addEventListener('click', (e) => {
        try { e.preventDefault(); e.stopPropagation(); } catch { /* ignore */ }
        if (isMainExtensionLoaded) return;
        try {
          if (typeof chrome !== 'undefined' && chrome.runtime) {
            chrome.runtime.sendMessage({ type: 'KP_TOGGLE_STATE' });
          }
        } catch { /* ignore */ }
      });

      keyboardBtn.addEventListener('click', (e) => {
        try { e.preventDefault(); e.stopPropagation(); } catch { /* ignore */ }
        if (isMainExtensionLoaded) return;
        if (!isExtensionEnabled) return;
        const next = !keyboardHelpVisible;
        applyEarlyKeyboardHelpVisibility(next);
        try {
          const payload = { [KEYBOARD_HELP_STORAGE_KEY]: next };
          chrome.storage.sync.set(payload).catch(() => {
            try { chrome.storage.local.set(payload).catch(() => {}); } catch { /* ignore */ }
          });
        } catch { /* ignore */ }
        renderEarlyControlStripKeyboard();
      });

      settingsBtn.addEventListener('click', (e) => {
        try { e.preventDefault(); e.stopPropagation(); } catch { /* ignore */ }
        // Settings popover requires the main content script; no-op until handoff.
      });

      collapseBtn.addEventListener('click', (e) => {
        try { e.preventDefault(); e.stopPropagation(); } catch { /* ignore */ }
        if (isMainExtensionLoaded) return;
        controlStripCollapsed = !controlStripCollapsed;
        applyEarlyControlStripCollapsedLayout();
        persistEarlyControlStripSettings({ collapsed: controlStripCollapsed });
      });

      closeBtn.addEventListener('click', (e) => {
        try { e.preventDefault(); e.stopPropagation(); } catch { /* ignore */ }
        if (isMainExtensionLoaded) return;
        controlStripDesiredVisible = false;
        applyEarlyControlStripVisibility();
        persistEarlyControlStripSettings({ visible: false });
      });

      root.appendChild(statusBtn);
      root.appendChild(modules);
      root.appendChild(collapseBtn);
      root.appendChild(closeBtn);

      (document.body || document.documentElement).appendChild(root);

      controlStripRoot = root;
      controlStripRefs = {
        statusBtn,
        statusDot,
        statusLabel,
        modules,
        moveBtn,
        keyboardBtn,
        settingsBtn,
        collapseBtn,
        closeBtn
      };

      renderEarlyControlStripStatus();
      renderEarlyControlStripKeyboard();
      applyEarlyControlStripCollapsedLayout();
      return controlStripRoot;
    } catch {
      return null;
    }
  }

  function applyEarlyControlStripVisibility() {
    if (isMainExtensionLoaded) return;
    ensureEarlyControlStripShell();
    if (!controlStripRoot) return;
    // Control strip stays available even when KeyPilot is disabled (On/Off re-enable).
    const show = !!controlStripDesiredVisible;
    try {
      controlStripRoot.hidden = !show;
      controlStripRoot.style.display = show ? 'flex' : 'none';
      controlStripRoot.style.pointerEvents = show ? 'auto' : 'none';
    } catch { /* ignore */ }
    if (show) {
      applyEarlyControlStripCollapsedLayout();
      renderEarlyControlStripStatus();
      renderEarlyControlStripKeyboard();
      syncEarlyControlStripOnboardingOffset();
    }
  }

  function applyEarlyControlStripFromSettingsObject(settingsObj) {
    const parsed = parseControlStripFromSettings(settingsObj);
    controlStripDesiredVisible = parsed.visible;
    controlStripCollapsed = parsed.collapsed;
    try {
      earlyPanelPositions = readEarlyPanelPositionsFromSettingsObj(settingsObj) || earlyPanelPositions;
    } catch { /* ignore */ }
    applyEarlyControlStripVisibility();
    // Re-apply dock positions when settings arrive (shells may already exist).
    try {
      if (controlStripRoot && controlStripRoot.isConnected) {
        earlyApplyPanelPosition(controlStripRoot, earlyPanelPositions && earlyPanelPositions.controlStrip, {
          margin: EARLY_STRIP_MARGIN_PX,
          defaultAnchor: 'top-left',
          defaultHeight: CONTROL_STRIP_HEIGHT_PX
        });
      }
    } catch { /* ignore */ }
    try {
      if (keyboardHelpRoot && keyboardHelpRoot.isConnected) {
        earlyApplyPanelPosition(keyboardHelpRoot, earlyPanelPositions && earlyPanelPositions.keyboardReference, {
          margin: EARLY_PANEL_MARGIN_PX,
          defaultAnchor: 'bottom-left',
          defaultWidth: 760,
          defaultHeight: 200
        });
      }
    } catch { /* ignore */ }
  }

  function setupControlStripStorageListener() {
    if (controlStripStorageListener || !chrome?.storage?.onChanged) return;
    controlStripStorageListener = (changes, areaName) => {
      if (isMainExtensionLoaded) return;
      if (!changes || (areaName !== 'sync' && areaName !== 'local')) return;
      if (!Object.prototype.hasOwnProperty.call(changes, SETTINGS_STORAGE_KEY)) return;
      try {
        const next = changes[SETTINGS_STORAGE_KEY]?.newValue;
        applyEarlyControlStripFromSettingsObject(next && typeof next === 'object' ? next : null);
      } catch { /* ignore */ }
    };
    try {
      chrome.storage.onChanged.addListener(controlStripStorageListener);
    } catch { /* ignore */ }
  }

  /**
   * Ensure the floating keyboard reference shell exists early (document_start).
   * The bundled extension will "adopt" this element later to avoid flicker.
   */
  function ensureEarlyFloatingKeyboardHelpShell() {
    if (isMainExtensionLoaded) return;
    if (keyboardHelpRoot && keyboardHelpRoot.isConnected) return;

    const doc = document;
    const root = doc.createElement('div');
    root.className = 'kp-floating-keyboard-help';
    root.hidden = true;
    root.setAttribute('role', 'dialog');
    root.setAttribute('aria-label', 'KeyPilot keyboard reference');
    root.setAttribute('data-kp-early-floating-keyboard', 'true');

    // Compact dark window chrome (inline so host pages can't override it).
    // Start fully hidden: never rely on the `hidden` attribute alone (Zapier etc.
    // override UA [hidden]{display:none} with author display rules).
    Object.assign(root.style, {
      position: 'fixed',
      left: '16px',
      bottom: '16px',
      width: '760px',
      // Symmetric with EARLY_PANEL_MARGIN_PX (16) on every edge — not 24 (asymmetric right/bottom).
      maxWidth: 'calc(100vw - 32px)',
      maxHeight: 'calc(100vh - 32px)',
      overflow: 'auto',
      zIndex: String(Z_FLOATING_KEYBOARD_HELP),
      background: 'rgba(10, 11, 14, 0.98)',
      color: 'rgba(248, 250, 252, 0.95)',
      // Match onboarding panel rim (light gray outline).
      border: '1px solid rgba(255,255,255,0.12)',
      borderRadius: '4px',
      boxShadow: '0 16px 40px rgba(0,0,0,0.55), 0 2px 8px rgba(0,0,0,0.35)',
      fontFamily: 'system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif',
      // Flex when shown (titlebar + body); explicit none until visibility is applied.
      display: 'none',
      flexDirection: 'column',
      pointerEvents: 'none'
    });
    try { root.setAttribute('aria-hidden', 'true'); } catch { /* ignore */ }
    try { root.classList.add('kpv2-hidden'); } catch { /* ignore */ }
    // Match popup.html theme tokens so the early-rendered keyboard matches the popup.
    try { applyPopupThemeVars(root); } catch { /* ignore */ }
    // Restore saved dock / free position (default bottom-left).
    try {
      earlyApplyPanelPosition(root, earlyPanelPositions && earlyPanelPositions.keyboardReference, {
        margin: EARLY_PANEL_MARGIN_PX,
        defaultAnchor: 'bottom-left',
        defaultWidth: 760,
        defaultHeight: 200
      });
    } catch { /* ignore */ }

    const header = doc.createElement('div');
    header.setAttribute('data-kp-floating-keyboard-titlebar', 'true');
    Object.assign(header.style, {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      gap: '8px',
      height: '28px',
      minHeight: '28px',
      maxHeight: '28px',
      boxSizing: 'border-box',
      padding: '0 6px 0 10px',
      margin: '0',
      borderBottom: '1px solid rgba(0,0,0,0.55)',
      background: 'linear-gradient(180deg, #1a1b1f 0%, #121316 100%)',
      flex: '0 0 auto'
    });

    const title = doc.createElement('div');
    title.textContent = 'Keyboard Reference';
    title.setAttribute('data-kp-floating-keyboard-title', 'true');
    Object.assign(title.style, {
      fontSize: '11px',
      fontWeight: '600',
      letterSpacing: '0.01em',
      textTransform: 'none',
      color: 'rgba(220, 220, 225, 0.9)',
      lineHeight: '28px',
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      margin: '0',
      padding: '0'
    });

    const hint = doc.createElement('div');
    hint.setAttribute('data-kp-floating-keyboard-hint', 'true');
    Object.assign(hint.style, {
      display: 'inline-flex',
      alignItems: 'center',
      gap: '4px',
      marginLeft: 'auto',
      fontSize: '10px',
      fontWeight: '500',
      letterSpacing: '0',
      color: 'rgba(140, 145, 155, 0.95)',
      padding: '0 4px',
      borderRadius: '0',
      border: 'none',
      background: 'transparent',
      lineHeight: '28px',
      whiteSpace: 'nowrap'
    });
    // "Press <kbd>K</kbd> to toggle" — key chip matches main extension titlebar.
    hint.appendChild(doc.createTextNode('Press '));
    const hintKbd = doc.createElement('kbd');
    hintKbd.setAttribute('data-kp-floating-keyboard-hint-key', 'true');
    hintKbd.textContent = 'K';
    Object.assign(hintKbd.style, {
      display: 'inline-block',
      fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
      fontSize: '10px',
      fontWeight: '600',
      lineHeight: '1.2',
      padding: '1px 5px',
      border: '1px solid rgba(255, 255, 255, 0.16)',
      borderBottomColor: 'rgba(0, 0, 0, 0.55)',
      borderRadius: '4px',
      background: 'linear-gradient(180deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.04) 100%)',
      color: 'rgba(230, 232, 238, 0.95)',
      boxShadow: '0 1px 0 rgba(0, 0, 0, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.06)',
      verticalAlign: 'middle'
    });
    hint.appendChild(hintKbd);
    hint.appendChild(doc.createTextNode(' to toggle'));
    try { hint.setAttribute('aria-label', 'Press K to toggle'); } catch { /* ignore */ }

    const closeBtn = doc.createElement('button');
    closeBtn.type = 'button';
    closeBtn.textContent = '×';
    closeBtn.setAttribute('aria-label', 'Close keyboard reference');
    closeBtn.setAttribute('data-kp-floating-keyboard-close', 'true');
    Object.assign(closeBtn.style, {
      width: '22px',
      height: '22px',
      minWidth: '22px',
      minHeight: '22px',
      borderRadius: '4px',
      border: 'none',
      background: 'transparent',
      color: 'rgba(200, 200, 205, 0.9)',
      cursor: 'pointer',
      fontSize: '15px',
      lineHeight: '20px',
      padding: '0',
      margin: '0',
      flex: '0 0 auto',
      boxShadow: 'none'
    });
    closeBtn.addEventListener('click', (e) => {
      // Match main extension behavior: hide without persisting.
      try { e.preventDefault(); e.stopPropagation(); } catch {}
      if (root) root.hidden = true;
    });

    header.appendChild(title);
    header.appendChild(hint);
    header.appendChild(closeBtn);

    const body = doc.createElement('div');
    body.setAttribute('data-kp-floating-keyboard-body', 'true');
    Object.assign(body.style, {
      padding: '0',
      margin: '0',
      border: 'none',
      background: 'transparent'
    });

    const keyboardContainer = doc.createElement('div');
    keyboardContainer.className = 'kp-floating-keyboard-help__keyboard';
    keyboardContainer.textContent = '';
    body.appendChild(keyboardContainer);

    root.appendChild(header);
    root.appendChild(body);

    // Attach to DOM (body may not exist at document_start).
    (doc.body || doc.documentElement).appendChild(root);

    keyboardHelpRoot = root;
    keyboardHelpKeyboardContainer = keyboardContainer;

    // Pre-render the keyboard immediately so the panel doesn't start as only a titlebar.
    renderEarlyKeyboard(keyboardContainer, { layoutId: keyboardLayoutId });
    // Reclamp after content has a real height (avoids free tops saved with h=0 going off-screen).
    try {
      earlyApplyPanelPosition(root, earlyPanelPositions && earlyPanelPositions.keyboardReference, {
        margin: EARLY_PANEL_MARGIN_PX,
        defaultAnchor: 'bottom-left',
        defaultWidth: 760,
        defaultHeight: 200
      });
    } catch { /* ignore */ }
    try {
      requestAnimationFrame(() => {
        try {
          earlyApplyPanelPosition(root, earlyPanelPositions && earlyPanelPositions.keyboardReference, {
            margin: EARLY_PANEL_MARGIN_PX,
            defaultAnchor: 'bottom-left',
            defaultWidth: 760,
            defaultHeight: 200
          });
        } catch { /* ignore */ }
      });
    } catch { /* ignore */ }
  }

  function updateKeyboardHelpHintForLayout(layoutId) {
    try {
      if (!keyboardHelpRoot) return;
      const hint = keyboardHelpRoot.querySelector('[data-kp-floating-keyboard-hint="true"]');
      if (!hint) return;
      const data = getEarlyKeyboardDataForLayout(layoutId || keyboardLayoutId);
      const binding = data?.bindings?.TOGGLE_KEYBOARD_HELP;
      const key = binding && (binding.displayKey || binding.keyLabel) ? String(binding.displayKey || binding.keyLabel) : 'K';

      while (hint.firstChild) hint.removeChild(hint.firstChild);
      hint.appendChild(document.createTextNode('Press '));
      let kbd = null;
      try { kbd = document.createElement('kbd'); } catch { kbd = null; }
      if (kbd) {
        kbd.setAttribute('data-kp-floating-keyboard-hint-key', 'true');
        kbd.textContent = key;
        Object.assign(kbd.style, {
          display: 'inline-block',
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
          fontSize: '10px',
          fontWeight: '600',
          lineHeight: '1.2',
          padding: '1px 5px',
          border: '1px solid rgba(255, 255, 255, 0.16)',
          borderBottomColor: 'rgba(0, 0, 0, 0.55)',
          borderRadius: '4px',
          background: 'linear-gradient(180deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.04) 100%)',
          color: 'rgba(230, 232, 238, 0.95)',
          boxShadow: '0 1px 0 rgba(0, 0, 0, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.06)',
          verticalAlign: 'middle'
        });
        hint.appendChild(kbd);
      } else {
        hint.appendChild(document.createTextNode(key));
      }
      hint.appendChild(document.createTextNode(' to toggle'));
      try { hint.setAttribute('aria-label', `Press ${key} to toggle`); } catch { /* ignore */ }
    } catch { /* ignore */ }
  }

  /**
   * Show/hide keyboard reference in a way that survives hostile host CSS.
   * Zapier (and other apps) override UA `[hidden]{display:none}` with author
   * `display` rules, so the `hidden` attribute alone is not enough — same
   * lesson as onboarding (`setOnboardingPanelVisible`) and key popovers.
   * @param {HTMLElement|null} root
   * @param {boolean} visible
   */
  function setEarlyKeyboardHelpRootVisible(root, visible) {
    if (!root) return;
    const show = !!visible;
    try {
      root.hidden = !show;
      root.setAttribute('aria-hidden', show ? 'false' : 'true');
      // Prefer !important so host author sheets cannot re-show a closed panel.
      root.style.setProperty('display', show ? 'flex' : 'none', 'important');
      root.style.setProperty('pointer-events', show ? 'auto' : 'none', 'important');
      if (!show) {
        try { root.classList.add('kpv2-hidden'); } catch { /* ignore */ }
      } else {
        try { root.classList.remove('kpv2-hidden'); } catch { /* ignore */ }
      }
    } catch { /* ignore */ }
  }

  function applyEarlyKeyboardHelpVisibility(visible) {
    if (isMainExtensionLoaded) return;
    keyboardHelpVisible = Boolean(visible);

    // If extension is disabled, keep it hidden but remember desired state.
    ensureEarlyFloatingKeyboardHelpShell();
    if (!keyboardHelpRoot) return;
    setEarlyKeyboardHelpRootVisible(
      keyboardHelpRoot,
      !!(isExtensionEnabled && keyboardHelpVisible)
    );
    try { renderEarlyControlStripKeyboard(); } catch { /* ignore */ }
  }

  async function getKeyboardHelpVisibleFromStorage() {
    const key = KEYBOARD_HELP_STORAGE_KEY;
    try {
      const syncResult = await chrome.storage.sync.get([key]);
      if (typeof syncResult?.[key] === 'boolean') return syncResult[key];
    } catch {}
    try {
      const localResult = await chrome.storage.local.get([key]);
      if (typeof localResult?.[key] === 'boolean') return localResult[key];
    } catch {}
    return false;
  }

  function setupKeyboardHelpStorageListener() {
    if (keyboardHelpStorageListener || !chrome?.storage?.onChanged) return;
    keyboardHelpStorageListener = (changes, areaName) => {
      if (isMainExtensionLoaded) return;
      if (!changes || (areaName !== 'sync' && areaName !== 'local')) return;
      if (!Object.prototype.hasOwnProperty.call(changes, KEYBOARD_HELP_STORAGE_KEY)) return;
      const next = Boolean(changes[KEYBOARD_HELP_STORAGE_KEY]?.newValue);
      applyEarlyKeyboardHelpVisibility(next);
    };
    try {
      chrome.storage.onChanged.addListener(keyboardHelpStorageListener);
    } catch {}
  }

  let cursorSettingsListener = null;

  function setupCursorSettingsListener() {
    if (cursorSettingsListener || !chrome?.storage?.onChanged) return;
    cursorSettingsListener = (changes, areaName) => {
      if (isMainExtensionLoaded) return;
      if (!changes || (areaName !== 'sync' && areaName !== 'local')) return;
      if (!Object.prototype.hasOwnProperty.call(changes, SETTINGS_STORAGE_KEY)) return;
      
      // Mark that settings changed so cursor will be reapplied
      cursorSettingsChanged = true;
      cursorApplied = false; // Force reapplication

      // Also refresh early keyboard layout selection (prevents layout flicker if user changes it
      // before the bundled content script has taken over).
      try {
        const next = changes[SETTINGS_STORAGE_KEY]?.newValue;
        const nextId = normalizeKeyboardLayoutId(next && typeof next === 'object' ? next.keyboardLayoutId : null);
        if (nextId && nextId !== keyboardLayoutId) {
          keyboardLayoutId = nextId;
          try { renderEarlyKeyboard(keyboardHelpKeyboardContainer, { layoutId: keyboardLayoutId }); } catch { /* ignore */ }
          updateKeyboardHelpHintForLayout(keyboardLayoutId);
        }
      } catch { /* ignore */ }
      
      if (isExtensionEnabled) {
        applyEarlyCursor().catch(() => {});
      }
    };
    try {
      chrome.storage.onChanged.addListener(cursorSettingsListener);
    } catch {}
  }

  /**
   * Handle mouse movement for early cursor tracking
   */
  function handleMouseMove(event) {
    if (!isExtensionEnabled) return;
    updateCursorPosition(event.clientX, event.clientY);
  }

  /**
   * Initialize early storage for faster state loading
   */
  function initEarlyStorage() {
    // Pre-warm storage connections for faster access
    if (typeof chrome !== 'undefined' && chrome.storage) {
      // Test storage availability early
      chrome.storage.sync.get(['keypilot_enabled', KEYBOARD_HELP_STORAGE_KEY, SETTINGS_STORAGE_KEY], (result) => {
        if (chrome.runtime.lastError) {
          // Storage not available, will fallback to localStorage
          isExtensionEnabled = true; // Default to enabled
          updateCursorVisibility();
          ensureEarlyFloatingKeyboardHelpShell();
          applyEarlyKeyboardHelpVisibility(false);
          ensureEarlyControlStripShell();
          applyEarlyControlStripVisibility();
          return;
        }
        isExtensionEnabled = result.keypilot_enabled !== false;
        keyboardHelpVisible = result[KEYBOARD_HELP_STORAGE_KEY] === true;
        let settingsObj = null;
        try {
          const st = result && result[SETTINGS_STORAGE_KEY] && typeof result[SETTINGS_STORAGE_KEY] === 'object' ? result[SETTINGS_STORAGE_KEY] : null;
          settingsObj = st;
          keyboardLayoutId = normalizeKeyboardLayoutId(st && st.keyboardLayoutId);
          earlyPanelPositions = readEarlyPanelPositionsFromSettingsObj(st);
        } catch {
          keyboardLayoutId = normalizeKeyboardLayoutId(keyboardLayoutId);
        }
        updateCursorVisibility();
        ensureEarlyFloatingKeyboardHelpShell();
        try { renderEarlyKeyboard(keyboardHelpKeyboardContainer, { layoutId: keyboardLayoutId }); } catch { /* ignore */ }
        updateKeyboardHelpHintForLayout(keyboardLayoutId);
        applyEarlyKeyboardHelpVisibility(keyboardHelpVisible);
        setupKeyboardHelpStorageListener();
        setupCursorSettingsListener();
        // Control strip early shell (adopted later by main bundle).
        applyEarlyControlStripFromSettingsObject(settingsObj);
        setupControlStripStorageListener();
      });
    } else {
      // No chrome storage available, default to enabled
      isExtensionEnabled = true;
      updateCursorVisibility();
      ensureEarlyFloatingKeyboardHelpShell();
      applyEarlyKeyboardHelpVisibility(false);
      ensureEarlyControlStripShell();
      applyEarlyControlStripVisibility();
    }
  }

  /**
   * Check extension state from storage
   */
  async function checkExtensionState() {
    let settingsObj = null;
    try {
      if (typeof chrome !== 'undefined' && chrome.storage) {
        const result = await chrome.storage.sync.get([
          'keypilot_enabled',
          KEYBOARD_HELP_STORAGE_KEY,
          SETTINGS_STORAGE_KEY
        ]);
        isExtensionEnabled = result.keypilot_enabled !== false; // Default to true
        keyboardHelpVisible = result[KEYBOARD_HELP_STORAGE_KEY] === true;
        try {
          settingsObj = result && result[SETTINGS_STORAGE_KEY] && typeof result[SETTINGS_STORAGE_KEY] === 'object'
            ? result[SETTINGS_STORAGE_KEY]
            : null;
          if (settingsObj) {
            keyboardLayoutId = normalizeKeyboardLayoutId(settingsObj.keyboardLayoutId);
            earlyPanelPositions = readEarlyPanelPositionsFromSettingsObj(settingsObj);
          }
        } catch { /* ignore */ }
      }
    } catch (error) {
      // Fallback to localStorage if Chrome storage fails
      try {
        const stored = localStorage.getItem('keypilot_enabled');
        isExtensionEnabled = stored !== 'false';
      } catch (e) {
        isExtensionEnabled = true; // Default enabled
      }
    }
    updateCursorVisibility();
    ensureEarlyFloatingKeyboardHelpShell();
    applyEarlyKeyboardHelpVisibility(keyboardHelpVisible);
    setupKeyboardHelpStorageListener();
    setupCursorSettingsListener();
    applyEarlyControlStripFromSettingsObject(settingsObj);
    setupControlStripStorageListener();
  }

  /**
   * Listen for extension state changes
   */
  function setupStateListener() {
    if (typeof chrome !== 'undefined' && chrome.runtime) {
      chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        if (message.type === 'EXTENSION_TOGGLED') {
          isExtensionEnabled = message.enabled;
          updateCursorVisibility();
          applyEarlyKeyboardHelpVisibility(keyboardHelpVisible);
          try { renderEarlyControlStripStatus(); } catch { /* ignore */ }
          try { renderEarlyControlStripKeyboard(); } catch { /* ignore */ }
        } else if (message.type === 'KP_TOGGLE_STATE' || message.type === 'KP_UPDATE_STATE') {
          // Broadcast from service worker after toggle; keep strip On/Off indicator current.
          if (typeof message.enabled === 'boolean') {
            isExtensionEnabled = message.enabled;
            updateCursorVisibility();
            applyEarlyKeyboardHelpVisibility(keyboardHelpVisible);
            try { renderEarlyControlStripStatus(); } catch { /* ignore */ }
            try { renderEarlyControlStripKeyboard(); } catch { /* ignore */ }
          }
        } else if (message.type === 'CURSOR_MODE_CHANGE') {
          currentMode = message.mode;
          // Early cursor only shows basic crosshair, mode changes handled by main extension
        }
      });
    }
  }

  /**
   * Inject essential CSS for early cursor styling
   */
  function injectEarlyCSS() {
    const existing = document.getElementById(STYLE_ID);
    if (existing) {
      try {
        existing.textContent = EARLY_CSS;
      } catch {}
      return;
    }
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = EARLY_CSS;
    
    // Inject at the end of head to prevent override, or use documentElement
    const target = document.head || document.documentElement;
    if (target) {
      target.appendChild(style);
    }
  }

  /**
   * Re-inject CSS to ensure it's not overridden by page styles
   */
  function reInjectCSS() {
    const existingStyle = document.getElementById(STYLE_ID);
    if (existingStyle) {
      existingStyle.remove();
    }
    injectEarlyCSS();
  }

  /**
   * Check if element is clickable for early detection
   */
  function isClickableElement(element) {
    if (!element || element.nodeType !== Node.ELEMENT_NODE) return false;
    
    const tagName = element.tagName.toLowerCase();
    const clickableTags = ['a', 'button', 'input', 'select', 'textarea'];
    
    return clickableTags.includes(tagName) || 
           element.hasAttribute('onclick') ||
           element.getAttribute('role') === 'button' ||
           element.getAttribute('role') === 'link';
  }

  /**
   * Start early DOM observation for clickable elements
   */
  function startEarlyDOMObservation() {
    if (!window.MutationObserver) return;

    earlyObserver = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        // Check added nodes
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            // Check the node itself
            if (isClickableElement(node)) {
              earlyClickableElements.add(node);
            }
            
            // Check child elements (lightweight scan)
            const clickables = node.querySelectorAll?.('a, button, input, select, textarea, [role="button"], [role="link"]');
            if (clickables) {
              clickables.forEach(el => earlyClickableElements.add(el));
            }
          }
        });

        // Remove deleted nodes
        mutation.removedNodes.forEach((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            earlyClickableElements.delete(node);
          }
        });
      });
    });

    // Start observing
    earlyObserver.observe(document.documentElement || document, {
      childList: true,
      subtree: true
    });

    // Initial scan of existing elements
    const existingClickables = document.querySelectorAll('a, button, input, select, textarea, [role="button"], [role="link"]');
    existingClickables.forEach(el => earlyClickableElements.add(el));
  }

  /**
   * Handle early keyboard events for immediate responsiveness
   */
  function handleEarlyKeydown(event) {
    // Handle Alt+K toggle immediately for responsiveness - ALWAYS check this regardless of extension state
    // Check for Alt key (covers both left and right Alt) and K key (case insensitive)
    if ((event.altKey || event.code === 'AltRight') && (event.key === 'k' || event.key === 'K' || event.code === 'KeyK')) {
      event.preventDefault();
      // Send toggle message to background script
      if (typeof chrome !== 'undefined' && chrome.runtime) {
        chrome.runtime.sendMessage({ type: 'KP_TOGGLE_STATE' });
      }
      return; // Don't process this key further
    }

    if (!isExtensionEnabled) return;

    // Store key event for main extension
    pendingKeyEvents.push({
      key: event.key,
      code: event.code,
      timestamp: Date.now(),
      ctrlKey: event.ctrlKey,
      altKey: event.altKey,
      shiftKey: event.shiftKey,
      metaKey: event.metaKey
    });

    // Keep only recent events (last 5 seconds)
    const fiveSecondsAgo = Date.now() - 5000;
    pendingKeyEvents = pendingKeyEvents.filter(e => e.timestamp > fiveSecondsAgo);
  }

  /**
   * Start early keyboard event capture
   */
  function startEarlyKeyboardCapture() {
    if (keyboardListenersActive) return;
    
    document.addEventListener('keydown', handleEarlyKeydown, { 
      passive: false, 
      capture: true 
    });
    keyboardListenersActive = true;
  }

  /**
   * Stop early keyboard event capture
   */
  function stopEarlyKeyboardCapture() {
    if (!keyboardListenersActive) return;
    
    document.removeEventListener('keydown', handleEarlyKeydown, { capture: true });
    keyboardListenersActive = false;
  }

  /**
   * Initialize early injection
   */
  function initEarlyInjection() {
    setupMainLoadedHandoffListener();
    // Initialize early storage for faster state loading
    initEarlyStorage();
    
    // Inject CSS immediately for proper styling
    injectEarlyCSS();
    
    // Start early DOM observation
    startEarlyDOMObservation();
    
    // Start early keyboard capture for immediate responsiveness
    startEarlyKeyboardCapture();
    
    // Apply CSS cursor immediately
    const applyCursor = () => {
      if (document.documentElement || document.body) {
        // Re-inject CSS after DOM is ready to prevent override
        reInjectCSS();
        // Start mouse tracking
        document.addEventListener('mousemove', handleMouseMove, { passive: true });
        // Ensure cursor is visible
        updateCursorVisibility();
        updateCursorPosition(window.innerWidth / 2, window.innerHeight / 2); // Start at center
        
        // Debug logging
        console.log('[KeyPilot Early] CSS cursor applied');
      } else {
        // Retry in next tick
        setTimeout(applyCursor, 1);
      }
    };

    applyCursor();
    setupStateListener();
  }

  /**
   * Expose early cursor API for main extension
   */
  window.KEYPILOT_EARLY = {
    getCursor: () => null, // No cursor element anymore
    getPosition: () => mousePosition,
    getClickableElements: () => Array.from(earlyClickableElements),
    getPendingKeyEvents: () => [...pendingKeyEvents],
    clearPendingKeyEvents: () => { pendingKeyEvents = []; },
    updatePosition: updateCursorPosition,
    setEnabled: (enabled) => {
      isExtensionEnabled = enabled;
      updateCursorVisibility();
    },
    cleanup: () => {
      // Remove CSS cursor
      if (document.documentElement) {
        try {
          document.documentElement.classList.remove(CURSOR_HIDDEN_CLASS);
          document.documentElement.style.removeProperty(CURSOR_VAR);
        } catch {}
        document.documentElement.style.cursor = '';
      }
      if (document.body) {
        document.body.style.cursor = '';
      }
      document.removeEventListener('mousemove', handleMouseMove);
      stopEarlyKeyboardCapture();
      if (earlyObserver) {
        earlyObserver.disconnect();
      }
    }
  };

  // Check extension state before initialization
  async function init() {
    setupMainLoadedHandoffListener();
    // Inject cursor CSS immediately so `checkExtensionState()` can apply the
    // cursor at document_start without waiting for the full early init.
    // NOTE: The rules are scoped to `html.kpv2-cursor-hidden` so they are inert unless enabled.
    injectEarlyCSS();

    // Onboarding + control strip shells should appear as early as possible to avoid UI pop-in.
    // The bundled content script will adopt this DOM and hydrate it later.
    setupEarlyOnboardingStorageSync();
    // Kick control-strip shell immediately (visibility refined once storage returns).
    try {
      ensureEarlyControlStripShell();
      applyEarlyControlStripVisibility();
    } catch { /* ignore */ }
    await checkExtensionState();

    // Always start keyboard capture for Alt+K toggle, regardless of extension state
    startEarlyKeyboardCapture();

    if (isExtensionEnabled) {
      initEarlyInjection();
    } else {
      // Keep control strip available so On/Off can re-enable before main bundle loads.
      try {
        ensureEarlyControlStripShell();
        applyEarlyControlStripVisibility();
        setupControlStripStorageListener();
        setupStateListener();
      } catch { /* ignore */ }
      console.log('[KeyPilot Early] Extension is disabled, skipping early injection but keeping Alt+K capture active');
    }
  }
  
  // Start initialization
  init();

})();
