import Editor, { type OnMount } from '@monaco-editor/react';
import { useEditorStore } from '../../store/useEditorStore';
import { useCallback } from 'react';

const isEmbedMode = typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('embed') === 'true';

function getLanguage(filename: string): string {
  const ext = filename.split('.').pop()?.toLowerCase() ?? '';
  if (['ino', 'cpp', 'c', 'cc', 'h', 'hpp'].includes(ext)) return 'cpp';
  if (ext === 'py') return 'python';
  if (ext === 'json') return 'json';
  if (ext === 'md') return 'markdown';
  return 'plaintext';
}

export const CodeEditor = () => {
  const { files, activeFileId, setFileContent, theme, fontSize } =
    useEditorStore();
  const activeFile = files.find((f) => f.id === activeFileId);

  // In embed mode (LMS exercises), disable copy-paste so students type code themselves
  const handleEditorMount: OnMount = useCallback((editor, monacoInstance) => {
    if (!isEmbedMode) return;

    // Disable paste action
    editor.addCommand(
      // eslint-disable-next-line no-bitwise
      monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyV,
      () => { /* noop — paste disabled */ },
    );

    // Disable cut (prevents copy-via-cut workaround)
    editor.addCommand(
      // eslint-disable-next-line no-bitwise
      monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyX,
      () => { /* noop — cut disabled */ },
    );

    // Disable context menu paste via DOM event
    editor.getDomNode()?.addEventListener('paste', (e) => e.preventDefault());
  }, []);

  return (
    <div style={{ height: '100%', width: '100%' }}>
      <Editor
        // key forces a fresh editor instance per file (preserves undo/redo per file)
        key={activeFileId}
        height="100%"
        language={activeFile ? getLanguage(activeFile.name) : 'cpp'}
        theme={theme}
        value={activeFile?.content ?? ''}
        onChange={(value) => {
          if (activeFileId) setFileContent(activeFileId, value || '');
        }}
        onMount={handleEditorMount}
        options={{
          minimap: { enabled: true },
          fontSize,
          automaticLayout: true,
          scrollBeyondLastLine: false,
          wordWrap: 'on',
        }}
      />
    </div>
  );
};
