/**
 * MarkdownEditor.jsx - Hoofd editor component
 *
 * Split-pane layout met:
 * - Links: Markdown textarea met toolbar en sneltoetsen
 * - Rechts: Live preview via dezelfde renderer als de pagina
 *
 * Wordt lazy-loaded en is alleen beschikbaar in dev mode
 * via /installatie?editor=<secret>
 */

import { useState, useRef, useCallback } from 'react';
import { parseDocument } from '../../lib/markdown/directives';
import { renderBlocks } from '../../lib/markdown/render';
import EditorToolbar from './EditorToolbar';
import ImageDropZone from './ImageDropZone';
import { useKeyboardShortcuts } from './useKeyboardShortcuts';

/**
 * @param {object} props
 * @param {string} props.content - Huidige Markdown content
 * @param {function} props.onContentChange - Callback bij wijzigingen
 */
export default function MarkdownEditor({ content, onContentChange, filename = 'installatie.md' }) {
  const [isOpen, setIsOpen] = useState(true);
  const [isDirty, setIsDirty] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [activeOS, setActiveOS] = useState('mac');
  const textareaRef = useRef(null);

  const handleChange = useCallback((newValue) => {
    onContentChange(newValue);
    setIsDirty(true);
  }, [onContentChange]);

  const handleSave = useCallback(async () => {
    if (!isDirty || isSaving) return;
    setIsSaving(true);

    try {
      const response = await fetch('/__editor/save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content, filename }),
      });

      const result = await response.json();
      if (!response.ok) throw new Error(result.error);

      setIsDirty(false);
    } catch (err) {
      alert(`Opslaan mislukt: ${err.message}`);
    } finally {
      setIsSaving(false);
    }
  }, [content, isDirty, isSaving]);

  // Keyboard shortcuts registreren
  useKeyboardShortcuts(textareaRef, handleChange, handleSave);

  // Preview renderen - try-catch zodat typefouten de editor niet crashen
  let frontmatter = {};
  let blocks = [];
  let parseError = null;
  try {
    const parsed = parseDocument(content);
    frontmatter = parsed.frontmatter;
    blocks = parsed.blocks;
  } catch (err) {
    parseError = err.message;
  }
  const context = { activeOS, setActiveOS };

  if (!isOpen) {
    return (
      <button
        onClick={() => setIsOpen(true)}
        className="fixed bottom-4 right-4 z-50 bg-coral-500 text-white px-4 py-2 rounded-lg shadow-lg hover:bg-coral-600 transition-colors font-medium"
      >
        Editor openen
      </button>
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex flex-col bg-warm-50">
      {/* Header bar */}
      <div className="flex items-center justify-between bg-warm-900 text-white px-4 py-2">
        <div className="flex items-center gap-3">
          <h2 className="font-display font-bold">Markdown Editor</h2>
          <span className="text-warm-400 text-sm">{filename}</span>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-warm-400 text-xs">
            Cmd+B vet | Cmd+I cursief | Cmd+K link | Cmd+S opslaan
          </span>
          <button
            onClick={() => setIsOpen(false)}
            className="ml-4 px-3 py-1 rounded text-warm-300 hover:text-white hover:bg-warm-700 transition-colors"
            title="Editor minimaliseren"
          >
            Minimaliseren
          </button>
          <button
            onClick={() => {
              if (isDirty && !confirm('Je hebt onopgeslagen wijzigingen. Weet je zeker dat je de editor wilt sluiten?')) return;
              setIsOpen(false);
            }}
            className="px-3 py-1 rounded text-warm-300 hover:text-white hover:bg-warm-700 transition-colors"
            title="Editor sluiten"
          >
            Sluiten
          </button>
        </div>
      </div>

      {/* Toolbar */}
      <EditorToolbar
        textareaRef={textareaRef}
        onChange={handleChange}
        onSave={handleSave}
        isDirty={isDirty}
        isSaving={isSaving}
      />

      {/* Split pane: editor links, preview rechts */}
      <div className="flex-1 flex overflow-hidden">
        {/* Markdown editor (links) */}
        <div className="w-1/2 flex flex-col border-r border-warm-200 min-h-0">
          <ImageDropZone
            textareaRef={textareaRef}
            onChange={handleChange}
            className="flex-1 flex flex-col min-h-0"
          >
            <textarea
              ref={textareaRef}
              value={content}
              onChange={(e) => handleChange(e.target.value)}
              className="flex-1 w-full p-4 font-mono text-sm text-warm-800 bg-white resize-none focus:outline-none min-h-0"
              spellCheck={false}
              placeholder="Typ hier je Markdown..."
            />
          </ImageDropZone>
        </div>

        {/* Live preview (rechts) */}
        <div className="w-1/2 overflow-y-auto bg-warm-50">
          <div className="max-w-3xl mx-auto p-8">
            {/* Preview header */}
            <div className="mb-6 pb-4 border-b border-warm-200">
              <span className="text-xs font-medium text-warm-400 uppercase tracking-wide">Preview</span>
              {/* OS toggle voor preview */}
              <div className="flex gap-2 mt-2">
                <button
                  onClick={() => setActiveOS('mac')}
                  className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                    activeOS === 'mac'
                      ? 'bg-coral-500 text-white'
                      : 'bg-warm-200 text-warm-600 hover:bg-warm-300'
                  }`}
                >
                  Mac
                </button>
                <button
                  onClick={() => setActiveOS('windows')}
                  className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                    activeOS === 'windows'
                      ? 'bg-coral-500 text-white'
                      : 'bg-warm-200 text-warm-600 hover:bg-warm-300'
                  }`}
                >
                  Windows
                </button>
              </div>
            </div>

            {/* Gerenderde content */}
            {parseError ? (
              <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700 text-sm">
                <p className="font-semibold">Parse error (wordt vanzelf opgelost tijdens typen):</p>
                <p className="font-mono mt-1">{parseError}</p>
              </div>
            ) : (
              <>
                {frontmatter.title && (
                  <h1 className="heading-hero mb-4">{frontmatter.title}</h1>
                )}
                {frontmatter.subtitle && (
                  <p className="text-xl text-warm-600 mb-10">{frontmatter.subtitle}</p>
                )}
                {renderBlocks(blocks, context)}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
