document.addEventListener('DOMContentLoaded', () => {
  let editorInstance;

  ClassicEditor
    .create(document.querySelector('#editor'), {
      ckfinder: {
        uploadUrl: 'backend/upload.php'
      },
      toolbar: [
        'heading', '|', 'bold', 'italic', 'link', '|',
        'bulletedList', 'numberedList', '|', 'imageUpload', '|', 'undo', 'redo'
      ],
      image: {
        toolbar: ['imageTextAlternative', 'imageStyle:full', 'imageStyle:side']
      }
    })
    .then(editor => {
      editorInstance = editor;
    })
    .catch(error => {
      console.error('Terjadi kesalahan:', error);
    });

  const form = document.getElementById('editorForm');
  const messageDiv = document.getElementById('message');

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const content = editorInstance.getData();

    try {
      const response = await fetch('backend/save.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `content=${encodeURIComponent(content)}`,
      });

      const result = await response.json();
      messageDiv.textContent = result.message;
      messageDiv.style.color = result.success ? 'green' : 'red';
    } catch (error) {
      messageDiv.textContent = 'Terjadi kesalahan saat menyimpan konten.';
      messageDiv.style.color = 'red';
    }
  });
});
