<script>
  import { onMount } from 'svelte';
  import { setupQWebChannel } from './qwc.js';        // just registers window.backend
  import { installEditorBridge } from './editorBridge.js'; // exposes editorLoad/LoadAuto/etc.
  // import JSONEditor from 'jsoneditor';
  import 'jsoneditor/dist/jsoneditor.css';
  import 'ace-builds/src-noconflict/ace';
  import 'ace-builds/src-noconflict/theme-monokai';
  import 'ace-builds/src-noconflict/theme-github';
  let editor;
  let container;

  // detect theme passed by Vite
  const mode = import.meta.env.MODE;
  const isDark = mode === 'dark';


  onMount(() => {
    // Do NOT call setupQWebChannel() or installEditorBridge() here anymore.
    // The page will be initialized by main.js. Just present an empty editor
    // until Python pushes data.
    if (window.editorLoad) {
      window.editorLoad({}, {}, { app_name: '—', version: null });
    }

    // Optional keyboard save:
    window.addEventListener('keydown', (e) => {
      const isSave = (e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'S');
      if (isSave) {
        e.preventDefault();
        if (window.editorTriggerSave) window.editorTriggerSave();
      }
    });
  });
</script>


<style>
  html, body, #app, .editor-container {
    margin: 0;
    padding: 0;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
  }
  .ace_hidden-cursors {
    cursor: default !important;
  }

  .editor-container {
    display: flex;
    flex-direction: column;
    background-color: var(--background-color);
    color: var(--text-color);
  }
  .ace_hidden-cursors {
    cursor: default !important;
  }
  body, .jsoneditor, .editor-container {
    cursor: default;
  }
  .jsoneditor {
    flex: 1;
    min-height: 0;
    background-color: var(--background-color);
    color: var(--text-color);
  }

  :root {
    --background-color: #ffffff;
    --text-color: #000000;
  }

  body.dark {
    --background-color: #1e1e1e;
    --text-color: #f0f0f0;
  }
  /* These apply only when body has the class .dark */
  body.dark .jsoneditor,
  body.dark .jsoneditor-outer,
  body.dark .ace_editor,
  body.dark .jsoneditor-menu {
    background-color: #1e1e1e;
    color: #ddd;
    border-color: #444;
  }

  body.dark .jsoneditor .ace_gutter {
    background: #2b2b2b;
    color: #aaa;
  }

  body.dark .jsoneditor .jsoneditor-statusbar {
    background-color: #2a2a2a;
    color: #ccc;
  }

  body.dark .jsoneditor-menu a,
  body.dark .jsoneditor-menu button {
    background-color: #2a2a2a;
    color: #ccc;
    border: none;
  }

  body.dark .jsoneditor-menu a:hover,
  body.dark .jsoneditor-menu button:hover {
    background-color: #333;
    color: #fff;
  }
.ace_editor, .ace_content, .ace_scroller, .ace_layer, .ace_hidden-cursors {
  cursor: default !important;
}
</style>

<div class="editor-container" bind:this={container}></div>
