(function () {
  function detectLocale(opts) {
    var fromOpts = String((opts && (opts.locale || opts.lc)) || '').toUpperCase();
    if (fromOpts === 'RU' || fromOpts === 'EN') return fromOpts;
    try {
      var fromLs = String(localStorage.getItem('ssforum_lc') || '').toUpperCase();
      if (fromLs === 'RU' || fromLs === 'EN') return fromLs;
    } catch (_) {}
    try {
      var fromQs = String(new URLSearchParams(window.location.search).get('lc') || '').toUpperCase();
      if (fromQs === 'RU' || fromQs === 'EN') return fromQs;
    } catch (_) {}
    try {
      var lang = String((navigator.language || navigator.userLanguage || '')).toLowerCase();
      if (lang.indexOf('ru') === 0) return 'RU';
    } catch (_) {}
    return 'EN';
  }

  function getRuLanguageUrl() {
    try {
      if (typeof chrome !== 'undefined' && chrome.runtime && typeof chrome.runtime.getURL === 'function') {
        return chrome.runtime.getURL('vendor/tinymce/langs/ru.js');
      }
      if (typeof browser !== 'undefined' && browser.runtime && typeof browser.runtime.getURL === 'function') {
        return browser.runtime.getURL('vendor/tinymce/langs/ru.js');
      }
    } catch (_) {}
    return 'vendor/tinymce/langs/ru.js';
  }

  function getHost(hostOrId) {
    if (!hostOrId) return null;
    if (typeof hostOrId === 'string') return document.getElementById(hostOrId);
    return hostOrId && hostOrId.nodeType === 1 ? hostOrId : null;
  }

  function create(hostOrId, options) {
    var host = getHost(hostOrId);
    if (!host || typeof window.tinymce === 'undefined') return null;

    var opts = options || {};
    var isInline = host.classList.contains('editor-box-inline');
    var textarea = document.createElement('textarea');
    var id = 'ssEditor_' + Math.random().toString(36).slice(2, 10);
    textarea.id = id;

    host.innerHTML = '';
    host.classList.add('editor-host-tiny');
    host.appendChild(textarea);

    var editor = null;
    var pendingFocus = false;

    var editorMinHeight = isInline ? 96 : 140;
    var editorMaxHeight = isInline ? 260 : 520;
    var locale = detectLocale(opts);

    window.tinymce.init({
      target: textarea,
      license_key: 'gpl',
      menubar: false,
      branding: false,
      promotion: false,
      statusbar: false,
      resize: false,
      min_height: editorMinHeight,
      max_height: editorMaxHeight,
      autoresize_bottom_margin: 8,
      placeholder: opts.placeholder || '',
      plugins: 'lists link code autoresize',
      toolbar: 'bold italic underline | numlist bullist blockquote | link code removeformat',
      toolbar_mode: 'scrolling',
      language: locale === 'RU' ? 'ru' : 'en',
      language_url: locale === 'RU' ? getRuLanguageUrl() : undefined,
      browser_spellcheck: true,
      contextmenu: false,
      link_default_target: '_blank',
      link_assume_external_targets: true,
      convert_urls: false,
      setup: function (ed) {
        editor = ed;
        ed.on('init', function () {
          if (pendingFocus) {
            pendingFocus = false;
            ed.focus();
          }
        });
      }
    });

    return {
      getHtml: function () {
        return editor ? (editor.getContent() || '').trim() : (textarea.value || '').trim();
      },
      getText: function () {
        return editor ? (editor.getContent({ format: 'text' }) || '').trim() : (textarea.value || '').trim();
      },
      isEmpty: function () {
        var text = editor ? (editor.getContent({ format: 'text' }) || '') : (textarea.value || '');
        return !String(text).trim();
      },
      clear: function () {
        if (editor) editor.setContent('');
        else textarea.value = '';
      },
      focus: function () {
        if (editor) editor.focus();
        else pendingFocus = true;
      },
      destroy: function () {
        if (editor) {
          editor.remove();
          editor = null;
        }
      }
    };
  }

  window.SSForumEditor = { create: create };
})();
