'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkToc from 'remark-toc';
import rehypeRaw from 'rehype-raw';
import rehypeSlug from 'rehype-slug';
import rehypeSanitize from 'rehype-sanitize';
import { Highlight, themes } from 'prism-react-renderer';
import {
  Eye,
  EyeOff,
  Edit3,
  X,
  CheckSquare2,
  Folder as FolderIcon,
} from 'lucide-react';
import { TagInput } from '@/components/ui/TagInput';
import { TagDisplay } from '@/components/ui/TagDisplay';
import { TaskSelectorWithData } from '@/components/shared/TaskSelectorWithData';
import { MermaidRenderer } from '@/components/ui/MermaidRenderer';
import { Tag, Task } from '@/lib/types';
import { Folder } from '@/services/folders';
import type { Components } from 'react-markdown';

// Fonction pour générer les composants Markdown réutilisables
const createMarkdownComponents = (
  isPreviewMode: boolean
): Partial<Components> => ({
  // Titres avec tailles différentes selon le mode
  h1: ({ children }: { children?: React.ReactNode }) => (
    <h1
      className={
        isPreviewMode
          ? 'text-4xl font-bold text-[var(--foreground)] mb-8 mt-10 first:mt-0 bg-gradient-to-r from-[var(--primary)] to-[var(--accent)] bg-clip-text text-transparent'
          : 'text-4xl font-bold text-[var(--foreground)] mb-8 mt-10 first:mt-0 bg-gradient-to-r from-[var(--primary)] to-[var(--accent)] bg-clip-text text-transparent'
      }
    >
      {children}
    </h1>
  ),
  h2: ({ children }: { children?: React.ReactNode }) => (
    <h2
      className={
        isPreviewMode
          ? 'text-3xl font-bold text-[var(--foreground)] mb-6 mt-8 border-b border-[var(--border)]/30 pb-2'
          : 'text-3xl font-bold text-[var(--foreground)] mb-6 mt-8 border-b border-[var(--border)]/30 pb-2'
      }
    >
      {children}
    </h2>
  ),
  h3: ({ children }: { children?: React.ReactNode }) => (
    <h3
      className={
        isPreviewMode
          ? 'text-2xl font-semibold text-[var(--foreground)] mb-4 mt-6'
          : 'text-2xl font-semibold text-[var(--foreground)] mb-4 mt-6'
      }
    >
      {children}
    </h3>
  ),
  h4: ({ children }: { children?: React.ReactNode }) => (
    <h4
      className={
        isPreviewMode
          ? 'text-xl font-semibold text-[var(--foreground)] mb-3 mt-5'
          : 'text-xl font-semibold text-[var(--foreground)] mb-3 mt-5'
      }
    >
      {children}
    </h4>
  ),
  h5: ({ children }: { children?: React.ReactNode }) => (
    <h5
      className={
        isPreviewMode
          ? 'text-lg font-semibold text-[var(--foreground)] mb-2 mt-4'
          : 'text-lg font-semibold text-[var(--foreground)] mb-2 mt-4'
      }
    >
      {children}
    </h5>
  ),
  h6: ({ children }: { children?: React.ReactNode }) => (
    <h6
      className={
        isPreviewMode
          ? 'text-base font-semibold text-[var(--foreground)] mb-2 mt-3 text-[var(--muted-foreground)]'
          : 'text-base font-semibold text-[var(--foreground)] mb-2 mt-3 text-[var(--muted-foreground)]'
      }
    >
      {children}
    </h6>
  ),
  p: ({ children }: { children?: React.ReactNode }) => (
    <p className="text-[var(--foreground)] mb-4 leading-relaxed">{children}</p>
  ),
  // Listes avec le même style partout
  ul: ({ children }: { children?: React.ReactNode }) => (
    <ul className="mb-0 pl-4">{children}</ul>
  ),
  ol: ({ children }: { children?: React.ReactNode }) => (
    <ol className="mb-0 pl-4 list-decimal list-inside">{children}</ol>
  ),
  li: ({
    children,
    className,
  }: {
    children?: React.ReactNode;
    className?: string;
  }) => {
    const isTaskListItem = className?.includes('task-list-item');

    if (isTaskListItem) {
      return (
        <li className="!m-0 py-0.5 text-[var(--foreground)]">{children}</li>
      );
    }

    return (
      <li className="!m-0 py-0.5 text-[var(--foreground)] flex items-start gap-2">
        <span className="w-1.5 h-1.5 bg-[var(--primary)] rounded-full mt-2 flex-shrink-0"></span>
        <span>{children}</span>
      </li>
    );
  },
  blockquote: ({ children }: { children?: React.ReactNode }) => (
    <blockquote className="border-l-4 border-[var(--primary)] pl-4 py-2 my-4 bg-[var(--card)]/20 backdrop-blur-sm rounded-r-lg">
      <div className="text-[var(--muted-foreground)] italic">{children}</div>
    </blockquote>
  ),
  code: (({
    inline,
    className,
    children,
    ...props
  }: {
    inline?: boolean;
    className?: string;
    children?: React.ReactNode;
  } & Record<string, unknown>) => {
    if (inline) {
      return (
        <code className="bg-[var(--card)]/60 px-2 py-1 rounded text-[var(--accent)] font-mono text-sm border border-[var(--border)]/40">
          {children}
        </code>
      );
    }
    return (
      <code className={className} {...props}>
        {children}
      </code>
    );
  }) as Components['code'],
  pre: ({ children }: { children?: React.ReactNode }) => {
    let codeElement: string | null = null;
    let className = '';

    if (React.isValidElement(children)) {
      const props = children.props as {
        children?: string;
        className?: string;
      };
      codeElement = props?.children || null;
      className = props?.className || '';
    }

    const isMermaid =
      className.includes('language-mermaid') ||
      (typeof codeElement === 'string' &&
        (codeElement.trim().startsWith('graph') ||
          codeElement.trim().startsWith('flowchart') ||
          codeElement.trim().startsWith('sequenceDiagram') ||
          codeElement.trim().startsWith('gantt') ||
          codeElement.trim().startsWith('pie') ||
          codeElement.trim().startsWith('gitgraph') ||
          codeElement.trim().startsWith('journey') ||
          codeElement.trim().startsWith('stateDiagram') ||
          codeElement.trim().startsWith('classDiagram') ||
          codeElement.trim().startsWith('erDiagram') ||
          codeElement.trim().startsWith('mindmap') ||
          codeElement.trim().startsWith('timeline')));

    if (isMermaid && typeof codeElement === 'string') {
      return (
        <div className="my-6">
          <MermaidRenderer chart={codeElement} />
        </div>
      );
    }

    const match = /language-(\w+)/.exec(className || '');
    const language = match ? match[1] : 'javascript';

    return (
      <Highlight
        theme={themes.vsDark}
        code={codeElement || ''}
        language={language}
      >
        {({
          className: highlightClassName,
          style,
          tokens,
          getLineProps,
          getTokenProps,
        }) => {
          // Supprimer les lignes vides à la fin
          const filteredTokens = tokens.filter((line, i) => {
            // Garder toutes les lignes sauf la dernière si elle est vide
            if (i === tokens.length - 1) {
              return (
                line.length > 0 &&
                line.some((token) => token.content.trim() !== '')
              );
            }
            return true;
          });

          return (
            <pre
              className="bg-[var(--card)]/60 border border-[var(--border)]/60 rounded-lg p-4 overflow-x-auto backdrop-blur-sm font-mono text-sm mb-6"
              style={{
                ...style,
                background: 'color-mix(in srgb, var(--card) 80%, transparent)',
              }}
            >
              <code className={highlightClassName}>
                {filteredTokens.map((line, i) => (
                  <div key={i} {...getLineProps({ line })}>
                    {line.map((token, key) => (
                      <span key={key} {...getTokenProps({ token })} />
                    ))}
                  </div>
                ))}
              </code>
            </pre>
          );
        }}
      </Highlight>
    );
  },
  a: ({ children, href }: { children?: React.ReactNode; href?: string }) => (
    <a
      href={href}
      className="text-[var(--primary)] hover:text-[var(--primary)]/80 underline decoration-[var(--primary)]/50 hover:decoration-[var(--primary)] transition-colors"
      target="_blank"
      rel="noopener noreferrer"
    >
      {children}
    </a>
  ),
  table: ({ children }: { children?: React.ReactNode }) => (
    <div className="overflow-x-auto my-6">
      <table className="min-w-full border border-[var(--border)]/60 rounded-lg overflow-hidden">
        {children}
      </table>
    </div>
  ),
  thead: ({ children }: { children?: React.ReactNode }) => (
    <thead className="bg-[var(--card)]/40">{children}</thead>
  ),
  tbody: ({ children }: { children?: React.ReactNode }) => (
    <tbody className="divide-y divide-[var(--border)]/60">{children}</tbody>
  ),
  tr: ({ children }: { children?: React.ReactNode }) => (
    <tr className="hover:bg-[var(--card)]/20 transition-colors">{children}</tr>
  ),
  th: ({ children }: { children?: React.ReactNode }) => (
    <th className="px-4 py-2 text-left text-[var(--foreground)] font-semibold border-b border-[var(--border)]/60">
      {children}
    </th>
  ),
  td: ({ children }: { children?: React.ReactNode }) => (
    <td className="px-4 py-2 text-[var(--foreground)]">{children}</td>
  ),
  hr: () => <hr className="my-8 border-t-2 border-[var(--border)]/30" />,
});

interface MarkdownEditorProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  className?: string;
  autoSave?: boolean;
  onSave?: () => void;
  tags?: string[];
  onTagsChange?: (tags: string[]) => void;
  availableTags?: Tag[];
  selectedTaskId?: string;
  selectedTask?: Task | null; // Objet Task complet pour l'affichage
  onTaskChange?: (task: Task | null) => void;
  selectedFolderId?: string;
  availableFolders?: Folder[];
  onFolderChange?: (folderId: string | null) => void;
  onCreateNote?: () => void;
  onToggleSidebar?: () => void;
  initialIsEditing?: boolean;
  onEditingChange?: (isEditing: boolean) => void;
}

export function MarkdownEditor({
  value,
  onChange,
  placeholder = 'Commencez à écrire votre note en markdown...',
  className = '',
  autoSave = false,
  onSave,
  tags = [],
  onTagsChange,
  availableTags = [],
  selectedTaskId,
  selectedTask,
  onTaskChange,
  selectedFolderId,
  availableFolders = [],
  onFolderChange,
  onCreateNote,
  onToggleSidebar,
  initialIsEditing = false,
  onEditingChange,
}: MarkdownEditorProps) {
  const [showPreview, setShowPreview] = useState(true); // Aperçu par défaut
  const [isEditing, setIsEditing] = useState(initialIsEditing); // Mode édition
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const autoSaveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const lastSavedValueRef = useRef(value);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Historique pour undo/redo
  const [history, setHistory] = useState<string[]>([value]);
  const [historyIndex, setHistoryIndex] = useState(0);

  // Fonction pour ajouter à l'historique
  const addToHistory = useCallback(
    (newValue: string) => {
      const newHistory = history.slice(0, historyIndex + 1);
      newHistory.push(newValue);
      setHistory(newHistory);
      setHistoryIndex(newHistory.length - 1);
    },
    [history, historyIndex]
  );

  // Fonction undo
  const undo = useCallback(() => {
    if (historyIndex > 0) {
      const newIndex = historyIndex - 1;
      setHistoryIndex(newIndex);
      onChange(history[newIndex]);
    }
  }, [historyIndex, history, onChange]);

  // Fonction redo
  const redo = useCallback(() => {
    if (historyIndex < history.length - 1) {
      const newIndex = historyIndex + 1;
      setHistoryIndex(newIndex);
      onChange(history[newIndex]);
    }
  }, [historyIndex, history, onChange]);

  // Fonction pour insérer du markdown
  const insertMarkdown = useCallback(
    (prefix: string, suffix: string, placeholder: string) => {
      const textarea = textareaRef.current;
      if (!textarea) return;

      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const selectedText = value.substring(start, end);
      const textToInsert = selectedText || placeholder;

      const newValue =
        value.substring(0, start) +
        prefix +
        textToInsert +
        suffix +
        value.substring(end);
      onChange(newValue);

      // Ajouter à l'historique
      addToHistory(newValue);

      // Restaurer la position du curseur
      setTimeout(() => {
        const newCursorPos = start + prefix.length + textToInsert.length;
        textarea.setSelectionRange(newCursorPos, newCursorPos);
        textarea.focus();
      }, 0);
    },
    [value, onChange, addToHistory]
  );

  // Fonction pour insérer au début de la ligne
  const insertAtLineStart = useCallback(
    (prefix: string) => {
      const textarea = textareaRef.current;
      if (!textarea) return;

      const start = textarea.selectionStart;
      value.substring(0, start).split('\n');
      const currentLineStart = value.substring(0, start).lastIndexOf('\n') + 1;
      const currentLine = value.substring(currentLineStart, start);

      // Vérifier si la ligne commence déjà par le préfixe
      const hasPrefix = currentLine.startsWith(prefix);
      let newValue: string;
      let newCursorPos: number;

      if (hasPrefix) {
        // Retirer le préfixe
        newValue =
          value.substring(0, currentLineStart) +
          currentLine.substring(prefix.length) +
          value.substring(start);
        newCursorPos = start - prefix.length;
      } else {
        // Ajouter le préfixe
        newValue =
          value.substring(0, currentLineStart) +
          prefix +
          currentLine +
          value.substring(start);
        newCursorPos = start + prefix.length;
      }

      onChange(newValue);

      // Ajouter à l'historique
      addToHistory(newValue);

      // Restaurer la position du curseur
      setTimeout(() => {
        textarea.setSelectionRange(newCursorPos, newCursorPos);
        textarea.focus();
      }, 0);
    },
    [value, onChange, addToHistory]
  );

  // Fonction de sauvegarde
  const handleSave = useCallback(() => {
    if (onSave && hasUnsavedChanges) {
      onSave();
      setHasUnsavedChanges(false);
      lastSavedValueRef.current = value;
    }
  }, [onSave, hasUnsavedChanges, value]);

  // Gestionnaire de raccourcis clavier
  const handleKeyDown = useCallback(
    (event: KeyboardEvent) => {
      const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
      const cmdKey = isMac ? event.metaKey : event.ctrlKey;

      if (!cmdKey) return;

      switch (event.key.toLowerCase()) {
        case 'n':
          event.preventDefault();
          onCreateNote?.();
          break;
        case 's':
          event.preventDefault();
          handleSave();
          break;
        case 'e':
          event.preventDefault();
          setIsEditing(!isEditing);
          onEditingChange?.(!isEditing);
          break;
        case 'b':
          event.preventDefault();
          insertMarkdown('**', '**', 'texte en gras');
          break;
        case 'i':
          event.preventDefault();
          insertMarkdown('*', '*', 'texte en italique');
          break;
        case 'k':
          if (event.shiftKey) {
            event.preventDefault();
            insertMarkdown('~~', '~~', 'texte barré');
          } else {
            event.preventDefault();
            insertMarkdown('[', '](url)', 'texte du lien');
          }
          break;
        case 'z':
          if (event.shiftKey) {
            event.preventDefault();
            redo();
          } else {
            event.preventDefault();
            undo();
          }
          break;
        case 'a':
          event.preventDefault();
          textareaRef.current?.select();
          break;
        case 'c':
        case 'v':
        case 'x':
          // Laisser les raccourcis de copier/coller/couper fonctionner normalement
          break;
        case 'f':
          event.preventDefault();
          // Rechercher dans le navigateur
          break;
        case 'g':
          event.preventDefault();
          // Rechercher suivant
          break;
        default:
          if (event.shiftKey) {
            switch (event.key) {
              case 'P':
                event.preventDefault();
                setShowPreview(!showPreview);
                break;
              case 'C':
                event.preventDefault();
                insertMarkdown('```\n', '\n```', 'code');
                break;
              case 'X':
                event.preventDefault();
                insertMarkdown('~~', '~~', 'texte barré');
                break;
              case 'H':
                event.preventDefault();
                insertAtLineStart('# ');
                break;
              case '2':
                event.preventDefault();
                insertAtLineStart('## ');
                break;
              case '3':
                event.preventDefault();
                insertAtLineStart('### ');
                break;
              case 'L':
                event.preventDefault();
                insertAtLineStart('- ');
                break;
              case 'O':
                event.preventDefault();
                insertAtLineStart('1. ');
                break;
              case 'Q':
                event.preventDefault();
                insertMarkdown('> ', '', 'citation');
                break;
              case 'S':
                event.preventDefault();
                onToggleSidebar?.();
                break;
            }
          }
          break;
      }
    },
    [
      isEditing,
      showPreview,
      handleSave,
      insertMarkdown,
      insertAtLineStart,
      undo,
      redo,
      onCreateNote,
      onToggleSidebar,
      onEditingChange,
    ]
  );

  // Attacher les raccourcis clavier
  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  // Auto-save (uniquement en mode édition)
  useEffect(() => {
    if (autoSave && hasUnsavedChanges && isEditing) {
      if (autoSaveTimeoutRef.current) {
        clearTimeout(autoSaveTimeoutRef.current);
      }

      autoSaveTimeoutRef.current = setTimeout(() => {
        handleSave();
      }, 2000);

      return () => {
        if (autoSaveTimeoutRef.current) {
          clearTimeout(autoSaveTimeoutRef.current);
        }
      };
    }
  }, [value, autoSave, hasUnsavedChanges, isEditing, handleSave]);

  // Détecter les changements
  useEffect(() => {
    if (value !== lastSavedValueRef.current) {
      setHasUnsavedChanges(true);
    }
  }, [value]);

  // Ajouter les changements manuels à l'historique
  useEffect(() => {
    if (value !== history[historyIndex]) {
      addToHistory(value);
    }
  }, [value, history, historyIndex, addToHistory]);

  // Réinitialiser le mode édition quand initialIsEditing devient true (nouvelle note)
  useEffect(() => {
    if (initialIsEditing) {
      setIsEditing(true);
      // Focus sur le textarea après un court délai pour s'assurer qu'il est monté
      setTimeout(() => {
        textareaRef.current?.focus();
      }, 100);
    }
  }, [initialIsEditing]);

  return (
    <div
      className={`flex flex-col h-full bg-[var(--card)]/40 backdrop-blur-md border border-[var(--border)]/60 rounded-lg overflow-hidden relative before:absolute before:inset-0 before:bg-gradient-to-br before:from-[color-mix(in_srgb,var(--primary)_8%,transparent)] before:via-[color-mix(in_srgb,var(--primary)_4%,transparent)] before:to-transparent before:opacity-80 before:pointer-events-none ${className}`}
    >
      {/* Tags et Tâche Input en mode édition */}
      {isEditing && (onTagsChange || onTaskChange) && (
        <div className="px-6 py-3 border-b border-[var(--border)]/30 bg-[var(--card)]/20 backdrop-blur-sm">
          <div className="flex items-center gap-6">
            {/* Tags Section */}
            {onTagsChange && (
              <div className="flex items-center gap-2 flex-1">
                <span className="text-sm font-medium text-[var(--foreground)]">
                  Tags:
                </span>
                <TagInput
                  tags={tags}
                  onChange={onTagsChange}
                  placeholder="Ajouter des tags..."
                  maxTags={10}
                  compactSuggestions={true}
                />
              </div>
            )}

            {/* Task Section */}
            {onTaskChange && (
              <div className="flex items-center gap-2 flex-1">
                <span className="text-sm font-medium text-[var(--foreground)]">
                  Tâche:
                </span>
                <TaskSelectorWithData
                  selectedTaskId={selectedTaskId}
                  onTaskSelect={onTaskChange}
                  placeholder="Associer à une tâche..."
                  className="flex-1"
                />
              </div>
            )}

            {onFolderChange && (
              <div className="flex items-center gap-2 flex-1">
                <FolderIcon className="w-4 h-4 text-[var(--muted-foreground)]" />
                <span className="text-sm font-medium text-[var(--foreground)]">
                  Dossier:
                </span>
                <select
                  value={selectedFolderId || '__none__'}
                  onChange={(e) => {
                    const value = e.target.value;
                    onFolderChange(value === '__none__' ? null : value);
                  }}
                  className="flex-1 px-3 py-1.5 text-sm bg-[var(--input)] border border-[var(--border)] rounded-lg text-[var(--foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--primary)]"
                >
                  <option value="__none__">Aucun dossier</option>
                  {availableFolders.map((folder) => (
                    <option key={folder.id} value={folder.id}>
                      {folder.name}
                    </option>
                  ))}
                </select>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Editor/Tags Area */}
      <div className="flex-1 flex overflow-hidden">
        {!isEditing ? (
          /* Mode Aperçu avec Tags */
          <div className="w-full flex flex-col">
            {/* Barre des tags et tâche */}
            {(tags && tags.length > 0) || selectedTask ? (
              <div className="p-3 border-b border-[var(--border)]/60 bg-[var(--card)]/40 backdrop-blur-md relative before:absolute before:inset-0 before:bg-gradient-to-r before:from-[color-mix(in_srgb,var(--primary)_8%,transparent)] before:via-[color-mix(in_srgb,var(--primary)_4%,transparent)] before:to-transparent before:opacity-80 before:pointer-events-none">
                <div className="flex items-start gap-6 relative z-10">
                  {/* Tags Section */}
                  {tags && tags.length > 0 && (
                    <div className="flex-1">
                      <span className="text-sm font-medium text-[var(--foreground)] mb-2 block">
                        Tags:
                      </span>
                      <TagDisplay
                        tags={tags}
                        availableTags={availableTags}
                        maxTags={10}
                        size="sm"
                        showColors={true}
                        showDot={false}
                      />
                    </div>
                  )}

                  {/* Task Section */}
                  {selectedTask && (
                    <div className="flex-1">
                      <span className="text-sm font-medium text-[var(--foreground)] mb-2 block">
                        Tâche associée:
                      </span>
                      <div className="flex items-center gap-2">
                        <CheckSquare2 className="w-4 h-4 text-[var(--primary)]" />
                        <span className="text-sm text-[var(--foreground)]">
                          {selectedTask.title}
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            ) : null}

            {/* Barre de l'aperçu */}
            <div className="p-3 border-b border-[var(--border)]/60 bg-[var(--card)]/40 backdrop-blur-md relative before:absolute before:inset-0 before:bg-gradient-to-r before:from-[color-mix(in_srgb,var(--primary)_8%,transparent)] before:via-[color-mix(in_srgb,var(--primary)_4%,transparent)] before:to-transparent before:opacity-80 before:pointer-events-none">
              <div className="flex items-center justify-between relative z-10">
                <span className="text-sm font-medium text-[var(--foreground)]">
                  Aperçu
                </span>
                <button
                  onClick={() => {
                    setIsEditing(true);
                    onEditingChange?.(true);
                  }}
                  className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-[var(--primary)]/80 hover:bg-[var(--primary)]/90 backdrop-blur-sm text-[var(--primary-foreground)] transition-all duration-200"
                >
                  <Edit3 className="w-3 h-3" />
                  Éditer
                </button>
              </div>
            </div>

            {/* Contenu de l'aperçu */}
            <div className="flex-1 overflow-auto p-6 bg-[var(--background)]/50 backdrop-blur-sm">
              <div className="prose prose-sm max-w-none prose-headings:text-[var(--foreground)] prose-p:text-[var(--foreground)] prose-strong:text-[var(--foreground)] prose-strong:font-bold prose-em:text-[var(--muted-foreground)] prose-code:text-[var(--accent)] prose-pre:bg-[var(--card)]/60 prose-pre:border prose-pre:border-[var(--border)]/60 prose-blockquote:border-[var(--primary)] prose-blockquote:text-[var(--muted-foreground)] prose-a:text-[var(--primary)] prose-table:border-[var(--border)]/60 prose-th:bg-[var(--card)]/40 prose-th:text-[var(--foreground)] prose-td:text-[var(--foreground)]">
                <ReactMarkdown
                  remarkPlugins={[
                    remarkGfm,
                    [
                      remarkToc,
                      {
                        heading: '(table[ -]of[ -])?contents?|toc|sommaire',
                        tight: true,
                      },
                    ],
                  ]}
                  rehypePlugins={[rehypeRaw, rehypeSlug, rehypeSanitize]}
                  components={createMarkdownComponents(true)}
                >
                  {value || "*Commencez à écrire pour voir l'aperçu...*"}
                </ReactMarkdown>
              </div>
            </div>
          </div>
        ) : (
          /* Mode Édition */
          <>
            {/* Editor */}
            <div
              className={`flex-1 flex flex-col ${showPreview ? 'w-1/2' : 'w-full'}`}
            >
              <div className="p-3 border-b border-[var(--border)]/60 bg-[var(--card)]/40 backdrop-blur-md relative before:absolute before:inset-0 before:bg-gradient-to-r before:from-[color-mix(in_srgb,var(--primary)_8%,transparent)] before:via-[color-mix(in_srgb,var(--primary)_4%,transparent)] before:to-transparent before:opacity-80 before:pointer-events-none">
                <div className="flex items-center justify-between relative z-10">
                  <span className="text-sm font-medium text-[var(--foreground)]">
                    Éditeur Markdown
                  </span>
                  <div className="flex items-center gap-2">
                    {hasUnsavedChanges && (
                      <span className="text-xs text-[var(--accent)] font-medium">
                        Non sauvegardé
                      </span>
                    )}
                    <button
                      onClick={() => {
                        setIsEditing(false);
                        onEditingChange?.(false);
                      }}
                      className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-[var(--card)]/60 hover:bg-[var(--card)]/80 backdrop-blur-sm text-[var(--foreground)] border border-[var(--border)]/40 hover:border-[var(--border)]/60 transition-all duration-200"
                    >
                      <X className="w-3 h-3" />
                      Fermer
                    </button>
                    <button
                      onClick={() => setShowPreview(!showPreview)}
                      className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-[var(--card)]/60 hover:bg-[var(--card)]/80 backdrop-blur-sm text-[var(--foreground)] border border-[var(--border)]/40 hover:border-[var(--border)]/60 transition-all duration-200"
                    >
                      {showPreview ? (
                        <EyeOff className="w-3 h-3" />
                      ) : (
                        <Eye className="w-3 h-3" />
                      )}
                      {showPreview ? 'Masquer' : 'Aperçu'}
                    </button>
                  </div>
                </div>
              </div>
              <div className="flex-1 overflow-hidden">
                <textarea
                  ref={textareaRef}
                  value={value}
                  onChange={(e) => onChange(e.target.value)}
                  placeholder={placeholder}
                  className="w-full h-full p-6 bg-[var(--background)]/50 backdrop-blur-sm text-[var(--foreground)] placeholder-[var(--muted-foreground)] resize-none border-none outline-none font-mono text-sm leading-relaxed"
                  style={{
                    fontFamily:
                      'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
                  }}
                />
              </div>
            </div>

            {/* Preview */}
            {showPreview && (
              <div className="w-1/2 flex flex-col border-l border-[var(--border)]/60">
                <div className="p-3 border-b border-[var(--border)]/60 bg-[var(--card)]/40 backdrop-blur-md relative before:absolute before:inset-0 before:bg-gradient-to-r before:from-[color-mix(in_srgb,var(--primary)_8%,transparent)] before:via-[color-mix(in_srgb,var(--primary)_4%,transparent)] before:to-transparent before:opacity-80 before:pointer-events-none">
                  <span className="text-sm font-medium text-[var(--foreground)] relative z-10">
                    Aperçu
                  </span>
                </div>
                <div className="flex-1 overflow-auto p-6 bg-[var(--background)]/50 backdrop-blur-sm">
                  <div className="prose prose-sm max-w-none prose-headings:text-[var(--foreground)] prose-p:text-[var(--foreground)] prose-strong:text-[var(--foreground)] prose-strong:font-bold prose-em:text-[var(--muted-foreground)] prose-code:text-[var(--accent)] prose-pre:bg-[var(--card)]/60 prose-pre:border prose-pre:border-[var(--border)]/60 prose-blockquote:border-[var(--primary)] prose-blockquote:text-[var(--muted-foreground)] prose-a:text-[var(--primary)] prose-table:border-[var(--border)]/60 prose-th:bg-[var(--card)]/40 prose-th:text-[var(--foreground)] prose-td:text-[var(--foreground)]">
                    <ReactMarkdown
                      remarkPlugins={[
                        remarkGfm,
                        [
                          remarkToc,
                          {
                            heading: '(table[ -]of[ -])?contents?|toc|sommaire',
                            tight: true,
                          },
                        ],
                      ]}
                      rehypePlugins={[rehypeRaw, rehypeSlug, rehypeSanitize]}
                      components={createMarkdownComponents(false)}
                    >
                      {value || "*Commencez à écrire pour voir l'aperçu...*"}
                    </ReactMarkdown>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
