// Disable text selection: inject CSS and clear any selection (including from scrollbar).
(function() {
  var style = document.createElement('style');
  style.id = 'kiosk-no-select';
  style.textContent = [
    'html, body, body *, body *::before, body *::after {',
    '  user-select: none !important; -webkit-user-select: none !important;',
    '  -moz-user-select: none !important; -ms-user-select: none !important;',
    '}',
    'input:focus, textarea:focus, [contenteditable="true"]:focus {',
    '  user-select: text !important; -webkit-user-select: text !important;',
    '}'
  ].join('');
  (document.head || document.documentElement).appendChild(style);

  function allowSelect(el) {
    return el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable);
  }

  function preventSelect(e) {
    if (allowSelect(e.target)) return;
    e.preventDefault();
  }

  function clearSelection() {
    var sel = document.getSelection();
    if (!sel || sel.rangeCount === 0) return;
    var node = sel.anchorNode;
    var el = node && (node.nodeType === 1 ? node : node.parentElement);
    if (el && !allowSelect(el)) sel.removeAllRanges();
  }

  document.addEventListener('selectstart', preventSelect, true);
  document.addEventListener('contextmenu', preventSelect, true);
  document.addEventListener('selectionchange', clearSelection, true);
  document.addEventListener('mousedown', function(e) { if (!allowSelect(e.target)) clearSelection(); }, true);
})();
