import { AUTO_SKIP_AT_FIELDS_LS, AUTO_SKIP_VALIDATED_ROWS_LS, DICT_AUTOCORRECT_ON_LOAD_LS, HIGHLIGHT_FLASH_MODE_LS, RECT_AUTO_ZOOM_LS, SNIPPET_TOGGLE_MODE_LS } from "./config/constants.js";
import { readLs } from "./core/storage.js";
import { ensureEditorDom } from "./core/dom.js";
import { loadBatches, loadSettings } from "./services/batch.js";
import {
  initFieldSelectionsFromDefaults,
  loadMergeHwrOrigColumnPreference,
  loadShortcutsPanelStartupPreference,
  loadShowConfColumnPreference,
  loadShowLotAssignmentPromptPreference,
  loadShowMergedHwrTextPreference,
  loadSuggestRankingModePreference,
  loadUserPreferencesFromServer,
  syncAutoSkipValidatedRowsUi,
  syncAutoSkipAtFieldsUi,
  syncDictAutocorrectOnLoadUi,
  syncMergeHwrOrigColumnUi,
  syncShowConfColumnUi,
  syncShowLotAssignmentPromptUi,
  syncShowMergedHwrTextUi,
  syncSuggestRankingModeUi,
} from "./services/preferences.js";
import { state, userPrefsStore, runtime } from './state/app-state.js';
import { initImagePanZoom, initZoomControls, syncRectAutoZoomToggleUi, syncRectFlashToggleUi, syncSnippetToggleUi } from "./ui/highlight.js";
import { initBdmImageControls } from "./ui/image-viewer.js";
import { toggleImporterPanel } from "./ui/importer.js";
import {
  applyLayoutColumns,
  initImagesPanelToggle,
  initSidebarResizer,
  initSplitResizer,
  syncImagesPanelToggleUi,
} from "./ui/layout.js";
import {
  initFieldsKindTabs,
  initPageFillModelSettings,
  initAutocorrectModelSettings,
  initProfilePanel,
  initSettingsTabs,
  initSubProjectsSettings,
  renderFieldsByKind,
  renderFieldsKindTabs,
  syncShortcutsStartupOptionUi,
  toggleSettingsPanel,
} from "./ui/settings/panel.js";
import { loadShortcutBindingOverrides, openShortcutsPanel, renderShortcutLists, toggleShortcutsPanel } from "./ui/shortcuts.js";
import { initFileMenu, initStatusDetails, publishDesktopBridge, setStatus, updateVisibleStatusBar } from "./ui/status-bar.js";
import { applyTheme, initFontScale, initTheme } from "./ui/theme.js";
import { initGatewayActivation } from "./ui/gateway-activation.js";
import "./ui/events.js";

export function bootstrap() {
  ensureEditorDom();
  initTheme();
  if (window.matchMedia) {
    const media = window.matchMedia("(prefers-color-scheme: dark)");
    const onThemeMediaChange = () => {
      if (runtime.themeMode === "system") applyTheme("system");
    };
    if (media.addEventListener) media.addEventListener("change", onThemeMediaChange);
    else if (media.addListener) media.addListener(onThemeMediaChange);
  }
  initFontScale();

  initZoomControls();
  if (userPrefsStore.auto_skip_validated_rows != null) {
    state.autoSkipValidatedRows = !!userPrefsStore.auto_skip_validated_rows;
  } else {
    state.autoSkipValidatedRows = readLs(AUTO_SKIP_VALIDATED_ROWS_LS) === "1";
  }
  syncAutoSkipValidatedRowsUi();
  if (userPrefsStore.auto_skip_at_fields != null) {
    state.autoSkipAtFields = !!userPrefsStore.auto_skip_at_fields;
  } else {
    state.autoSkipAtFields = readLs(AUTO_SKIP_AT_FIELDS_LS) === "1";
  }
  syncAutoSkipAtFieldsUi();
  if (userPrefsStore.dict_autocorrect_on_load != null) {
    state.dictAutocorrectOnLoad = !!userPrefsStore.dict_autocorrect_on_load;
  } else {
    state.dictAutocorrectOnLoad = readLs(DICT_AUTOCORRECT_ON_LOAD_LS) === "1";
  }
  syncDictAutocorrectOnLoadUi();
  if (userPrefsStore.highlight_flash_mode != null) {
    state.highlightFlashMode = !!userPrefsStore.highlight_flash_mode;
  } else {
    state.highlightFlashMode = readLs(HIGHLIGHT_FLASH_MODE_LS) === "1";
  }
  if (userPrefsStore.rect_auto_zoom != null) {
    state.rectAutoZoomEnabled = !!userPrefsStore.rect_auto_zoom;
  } else {
    state.rectAutoZoomEnabled = readLs(RECT_AUTO_ZOOM_LS) !== "0";
  }
  if (userPrefsStore.snippet_enabled != null) {
    state.snippetEnabled = !!userPrefsStore.snippet_enabled;
  } else {
    state.snippetEnabled = readLs(SNIPPET_TOGGLE_MODE_LS) !== "0";
  }
  syncRectFlashToggleUi();
  syncRectAutoZoomToggleUi();
  syncSnippetToggleUi();
  initSettingsTabs();
  initPageFillModelSettings();
  initAutocorrectModelSettings();
  initSubProjectsSettings();
  initProfilePanel();
  initFieldsKindTabs();
  renderFieldsKindTabs();
  loadShortcutsPanelStartupPreference();
  loadShortcutBindingOverrides();
  loadShowConfColumnPreference();
  loadMergeHwrOrigColumnPreference();
  loadShowMergedHwrTextPreference();
  loadShowLotAssignmentPromptPreference();
  loadSuggestRankingModePreference();
  syncShortcutsStartupOptionUi();
  syncShowConfColumnUi();
  syncMergeHwrOrigColumnUi();
  syncShowMergedHwrTextUi();
  syncShowLotAssignmentPromptUi();
  syncSuggestRankingModeUi();
  renderShortcutLists();
  initFieldSelectionsFromDefaults();
  renderFieldsByKind(state.selectedFieldsKind);
  toggleSettingsPanel(false);
  toggleShortcutsPanel(false);
  toggleImporterPanel(false);
  if (state.showShortcutsOnStartup) {
    openShortcutsPanel();
  }
  initImagesPanelToggle();
  applyLayoutColumns();
  syncImagesPanelToggleUi();
  initSidebarResizer();
  initSplitResizer();
  initImagePanZoom();
  initBdmImageControls();
  initFileMenu();
  initStatusDetails();
  initGatewayActivation();
  publishDesktopBridge();
  updateVisibleStatusBar();

  loadSettings()
    .then(() => loadUserPreferencesFromServer())
    .then(() => renderFieldsByKind(state.selectedFieldsKind))
    .then(loadBatches)
    .catch((e) => setStatus(e.message, true));
}
