export default function CodeEditorPlugin() {
  let isOpen = false;
  let container;

  function toggleEditor() {
    if (!container) return;
    isOpen = !isOpen;
    container.style.display = isOpen ? 'block' : 'none';
  }

  function createEditor(container) {
    container.innerHTML = `
      <div style="display: flex; flex-direction: column; height: 100%;">
        <div style="display: flex; flex: 1;">
          <textarea id="html-editor" placeholder="HTML" style="flex: 1; margin: 2px;"></textarea>
          <textarea id="css-editor" placeholder="CSS" style="flex: 1; margin: 2px;"></textarea>
          <textarea id="js-editor" placeholder="JS" style="flex: 1; margin: 2px;"></textarea>
        </div>
        <button id="run-button" style="margin-top: 4px;">▶ Run</button>
        <iframe id="preview-frame" sandbox="allow-scripts allow-modals"
                style="flex: none; height: 180px; width: 100%; border: 1px solid #ccc; margin-top: 5px;"></iframe>
      </div>
    `;

    const htmlEl = container.querySelector('#html-editor');
    const cssEl = container.querySelector('#css-editor');
    const jsEl = container.querySelector('#js-editor');
    const iframe = container.querySelector('#preview-frame');
    const runBtn = container.querySelector('#run-button');

    htmlEl.value = `<div id="box">Hello!</div>`;
    cssEl.value = `#box { background: lightblue; padding: 1em; }`;
    jsEl.value = `document.getElementById('box').onclick = () => alert('Clicked!');`;

    runBtn.onclick = () => {
      const html = htmlEl.value;
      const css = cssEl.value;
      const js = jsEl.value.replace(/<\/script>/g, '<\\/script>');

      const fullDoc = `
<!DOCTYPE html>
<html><head><style>${css}</style></head><body>
${html}
<script>${js}<\/script>
</body></html>`;

      const blob = new Blob([fullDoc], { type: 'text/html' });
      const url = URL.createObjectURL(blob);
      iframe.src = url;

      if (iframe._oldUrl) URL.revokeObjectURL(iframe._oldUrl);
      iframe._oldUrl = url;
    };

    runBtn.click();
  }

  function addCodeEditorButton() {
    const container = document.querySelector('#customcontrols ul');

    if (!container) {
      console.warn('customcontrols > ul 요소를 찾을 수 없습니다. customcontrols 플러그인이 로드되었는지 확인하세요.');
      return;
    }

    const li = document.createElement('li');

    const button = document.createElement('a');
    button.className = 'reveal-custom-control-button';
    button.title = '코드 편집기 열기/닫기';
    button.onclick = toggleEditor;

    const icon = document.createElement('i');
    icon.className = 'fas fa-code';
    button.appendChild(icon);

    li.appendChild(button);
    container.appendChild(li);
  }

  return {
    id: 'code-editor-plugin',
    init(deck) {
      deck.on('ready', () => {
        addCodeEditorButton();

        // 코드 패널 생성 (오버레이 아님)
        container = document.createElement('div');
        container.id = 'code-editor-panel';
        container.style.cssText = `
          position: absolute;
          top: 0;
          right: 0;
          width: 40%;
          height: 100%;
          z-index: 10;
          background: white;
          border-left: 1px solid #ccc;
          padding: 8px;
          display: none;
          box-shadow: -4px 0 12px rgba(0,0,0,0.2);
          overflow: auto;
        `;

        // 슬라이드에 부착
        const slide = deck.getCurrentSlide();
        slide.appendChild(container);

        createEditor(container);

        // 슬라이드 변경 시 에디터 제거 & 재추가
        deck.on('slidechanged', (event) => {
          container.style.display = 'none';
          isOpen = false;
          event.currentSlide.appendChild(container);
        });
      });
    }
  };
}