/**
 * Lexical WYSIWYG Editor Field for Puck
 *
 * Provides a rich text editing experience within Puck's visual editor.
 * Lexical is designed for React and handles state management cleanly.
 */

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
import { ListPlugin } from '@lexical/react/LexicalListPlugin';
import { LinkPlugin } from '@lexical/react/LexicalLinkPlugin';
import { HeadingNode, QuoteNode } from '@lexical/rich-text';
import { ListNode, ListItemNode } from '@lexical/list';
import { LinkNode, AutoLinkNode } from '@lexical/link';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import {
  $getRoot,
  $getSelection,
  $isRangeSelection,
  $createParagraphNode,
  FORMAT_TEXT_COMMAND,
  FORMAT_ELEMENT_COMMAND,
  UNDO_COMMAND,
  REDO_COMMAND,
  EditorState,
  ElementFormatType,
  LexicalEditor,
} from 'lexical';
import { INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND } from '@lexical/list';
import {
  $setBlocksType,
  $patchStyleText,
  $getSelectionStyleValueForProperty,
} from '@lexical/selection';
import { $createHeadingNode, $createQuoteNode } from '@lexical/rich-text';
import { ImageNode, ImagePlugin, ImageInsertPopover, INSERT_IMAGE_COMMAND } from './ImageNode';
import { useImageUpload } from '@/hooks/useImageUpload';
import { LinkInsertPopover } from './LinkInsertPopover';
import { FloatingLinkEditorPlugin } from './FloatingLinkEditor';
import { $selectionTouchesList, $anchorAlignment } from './lexical-alignment-utils';

// AMSOIL brand palette for text colors
const BRAND_COLORS = [
  { label: 'Primary Blue', value: '#093b66' },
  { label: 'Accent Orange', value: '#f8981d' },
  { label: 'Black', value: '#000000' },
  { label: 'Gray', value: '#757575' },
];

const FONT_SIZES = [12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];

interface LexicalFieldProps {
  value: string;
  onChange: (value: string) => void;
  enableMediaLibrary?: boolean;
}

// Toolbar button styles
const toolbarButtonStyle: React.CSSProperties = {
  padding: '0.25rem 0.5rem',
  border: '1px solid #d1d5db',
  borderRadius: '4px',
  background: 'white',
  color: '#000',
  cursor: 'pointer',
  fontSize: '0.875rem',
  minWidth: '2rem',
};

// Theme for Lexical editor
const theme = {
  paragraph: 'lexical-paragraph',
  heading: {
    h2: 'lexical-heading-h2',
    h3: 'lexical-heading-h3',
    h4: 'lexical-heading-h4',
  },
  list: {
    ul: 'lexical-list-ul',
    ol: 'lexical-list-ol',
    listitem: 'lexical-list-item',
  },
  quote: 'lexical-quote',
  link: 'lexical-link',
  text: {
    bold: 'lexical-text-bold',
    italic: 'lexical-text-italic',
    strikethrough: 'lexical-text-strikethrough',
    underline: 'lexical-text-underline',
  },
};

// Plugin to load initial HTML content
function InitialContentPlugin({ initialHtml }: { initialHtml: string }) {
  const [editor] = useLexicalComposerContext();
  const hasInitialized = useRef(false);

  useEffect(() => {
    if (hasInitialized.current || !initialHtml) return;
    hasInitialized.current = true;

    editor.update(() => {
      const parser = new DOMParser();
      const dom = parser.parseFromString(initialHtml, 'text/html');
      const nodes = $generateNodesFromDOM(editor, dom);
      const root = $getRoot();
      root.clear();
      nodes.forEach((node) => root.append(node));
    });
  }, [editor, initialHtml]);

  return null;
}

// Toolbar component
function Toolbar({ enableMediaLibrary }: { enableMediaLibrary?: boolean }) {
  const [editor] = useLexicalComposerContext();
  const [showColorPicker, setShowColorPicker] = useState(false);
  const [customColor, setCustomColor] = useState('#000000');
  const [showImagePopover, setShowImagePopover] = useState(false);
  const [showLinkPopover, setShowLinkPopover] = useState(false);
  const [currentFontSize, setCurrentFontSize] = useState('');
  // '' is Lexical's default element format, which renders as left-aligned
  const [currentAlign, setCurrentAlign] = useState<ElementFormatType>('');
  // Alignment is disabled inside lists: Lexical exports <li text-align> but
  // never re-imports it, so it would silently vanish on the next edit.
  const [alignDisabled, setAlignDisabled] = useState(false);
  const colorPickerRef = useRef<HTMLDivElement>(null);
  const imageInputRef = useRef<HTMLInputElement>(null);
  const imageTriggerRef = useRef<HTMLDivElement>(null);
  const linkTriggerRef = useRef<HTMLDivElement>(null);
  const { uploadImage, isUploading } = useImageUpload();

  // Sync font size dropdown with current cursor position
  useEffect(() => {
    return editor.registerUpdateListener(({ editorState }) => {
      editorState.read(() => {
        const selection = $getSelection();
        if (!$isRangeSelection(selection)) {
          setCurrentFontSize('');
          return;
        }
        // Check inline style first (covers explicitly-set sizes)
        const size = $getSelectionStyleValueForProperty(selection, 'font-size', '');
        const match = size.match(/^(\d+)px$/);
        if (match) {
          setCurrentFontSize(match[1]);
          return;
        }
        // Fall back to computed style for collapsed selections (cursor, no highlight)
        // For non-collapsed selections with mixed sizes, show "Size" placeholder
        if (!selection.isCollapsed()) {
          setCurrentFontSize('');
          return;
        }
        const node = selection.getNodes()[0];
        const element = editor.getElementByKey(node.getKey());
        if (element) {
          const computed = window.getComputedStyle(element).fontSize;
          const computedMatch = computed.match(/^([\d.]+)px$/);
          setCurrentFontSize(computedMatch ? String(Math.round(parseFloat(computedMatch[1]))) : '');
        } else {
          setCurrentFontSize('');
        }
      });
    });
  }, [editor]);

  // Sync alignment buttons with the block at the cursor. Every block type in
  // this editor (paragraph, heading, quote) is a direct child of root, so its
  // top-level element IS the block whose format the align command targets — the
  // one exception is list items, nested under a ListNode, where alignment is
  // unsupported (see alignDisabled).
  useEffect(() => {
    return editor.registerUpdateListener(({ editorState }) => {
      editorState.read(() => {
        const selection = $getSelection();
        if (!$isRangeSelection(selection)) {
          // No range selection (blur, node/decorator selection): clear stale
          // toolbar state instead of leaving the buttons stuck disabled/active.
          setAlignDisabled(false);
          setCurrentAlign('');
          return;
        }
        const touchesList = $selectionTouchesList(selection);
        setAlignDisabled(touchesList);
        // Only surface an active alignment when it can actually be applied.
        setCurrentAlign(touchesList ? '' : $anchorAlignment(selection));
      });
    });
  }, [editor]);

  // Close color picker when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (colorPickerRef.current && !colorPickerRef.current.contains(e.target as Node)) {
        setShowColorPicker(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const formatBold = useCallback(() => {
    editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'bold');
  }, [editor]);

  const formatItalic = useCallback(() => {
    editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'italic');
  }, [editor]);

  const formatStrikethrough = useCallback(() => {
    editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'strikethrough');
  }, [editor]);

  const formatHeading = useCallback(
    (level: 'h2' | 'h3' | 'h4') => {
      editor.update(() => {
        const selection = $getSelection();
        if ($isRangeSelection(selection)) {
          $setBlocksType(selection, () => $createHeadingNode(level));
        }
      });
    },
    [editor]
  );

  const formatParagraph = useCallback(() => {
    editor.update(() => {
      const selection = $getSelection();
      if ($isRangeSelection(selection)) {
        $setBlocksType(selection, () => $createParagraphNode());
      }
    });
  }, [editor]);

  const formatBulletList = useCallback(() => {
    editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
  }, [editor]);

  const formatNumberedList = useCallback(() => {
    editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
  }, [editor]);

  const formatQuote = useCallback(() => {
    editor.update(() => {
      const selection = $getSelection();
      if ($isRangeSelection(selection)) {
        $setBlocksType(selection, () => $createQuoteNode());
      }
    });
  }, [editor]);

  const formatAlign = useCallback(
    (alignment: ElementFormatType) => {
      editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, alignment);
    },
    [editor]
  );

  const applyFontSize = useCallback(
    (size: number) => {
      editor.update(() => {
        const selection = $getSelection();
        if ($isRangeSelection(selection)) {
          $patchStyleText(selection, { 'font-size': `${size}px` });
        }
      });
    },
    [editor]
  );

  const applyColor = useCallback(
    (color: string) => {
      editor.update(() => {
        const selection = $getSelection();
        if ($isRangeSelection(selection)) {
          $patchStyleText(selection, { color });
        }
      });
      setShowColorPicker(false);
    },
    [editor]
  );

  const handleImageUpload = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (!file) return;

      try {
        const url = await uploadImage(file, 'general');
        editor.focus();
        editor.dispatchCommand(INSERT_IMAGE_COMMAND, {
          src: url,
          altText: file.name.replace(/\.[^.]+$/, ''),
        });
      } catch {
        // Error is handled by the useImageUpload hook
      }

      if (imageInputRef.current) {
        imageInputRef.current.value = '';
      }
    },
    [editor, uploadImage]
  );

  const undo = useCallback(() => {
    editor.dispatchCommand(UNDO_COMMAND, undefined);
  }, [editor]);

  const redo = useCallback(() => {
    editor.dispatchCommand(REDO_COMMAND, undefined);
  }, [editor]);

  const alignButtonStyle = (target: ElementFormatType): React.CSSProperties => {
    const isActive =
      !alignDisabled && (currentAlign === target || (target === 'left' && currentAlign === ''));
    return {
      ...toolbarButtonStyle,
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      ...(alignDisabled ? { opacity: 0.4, cursor: 'not-allowed' } : {}),
      ...(isActive ? { background: '#e0e7ff', border: '1px solid #093b66' } : {}),
    };
  };
  const alignTitle = (base: string) =>
    alignDisabled ? 'Alignment is not available inside lists' : base;

  return (
    <div
      role="toolbar"
      aria-label="Text formatting"
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: '0.25rem',
        padding: '0.5rem',
        borderBottom: '1px solid #d1d5db',
        background: '#f9fafb',
        alignItems: 'center',
        borderTopLeftRadius: '6px',
        borderTopRightRadius: '6px',
        overflow: 'visible',
        position: 'relative',
      }}
    >
      <button
        type="button"
        onClick={formatBold}
        style={toolbarButtonStyle}
        title="Bold"
        aria-label="Bold"
      >
        <strong>B</strong>
      </button>
      <button
        type="button"
        onClick={formatItalic}
        style={toolbarButtonStyle}
        title="Italic"
        aria-label="Italic"
      >
        <em>I</em>
      </button>
      <button
        type="button"
        onClick={formatStrikethrough}
        style={toolbarButtonStyle}
        title="Strikethrough"
        aria-label="Strikethrough"
      >
        <s>S</s>
      </button>

      <span style={{ width: '1px', background: '#d1d5db', margin: '0 0.25rem', height: '24px' }} />

      {/* Font Size Dropdown */}
      <select
        onChange={(e) => applyFontSize(parseInt(e.target.value, 10))}
        value={currentFontSize}
        style={{
          ...toolbarButtonStyle,
          minWidth: '60px',
          appearance: 'auto',
        }}
        title="Font Size"
        aria-label="Font Size"
      >
        <option value="" disabled>
          Size
        </option>
        {FONT_SIZES.map((size) => (
          <option key={size} value={String(size)}>
            {size}px
          </option>
        ))}
      </select>

      {/* Color Picker */}
      <div style={{ position: 'relative' }} ref={colorPickerRef}>
        <button
          type="button"
          onClick={() => setShowColorPicker(!showColorPicker)}
          style={{
            ...toolbarButtonStyle,
            display: 'flex',
            alignItems: 'center',
            gap: '4px',
          }}
          title="Text Color"
          aria-label="Text Color"
        >
          <span>A</span>
          <span
            style={{
              width: '14px',
              height: '4px',
              backgroundColor: customColor,
              display: 'block',
            }}
          />
        </button>
        {showColorPicker && (
          <div
            style={{
              position: 'absolute',
              top: '100%',
              left: 0,
              zIndex: 1000,
              background: 'white',
              border: '1px solid #d1d5db',
              borderRadius: '6px',
              padding: '0.5rem',
              boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
              minWidth: '160px',
            }}
          >
            <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap', marginBottom: '0.5rem' }}>
              {BRAND_COLORS.map((c) => (
                <button
                  key={c.value}
                  type="button"
                  onClick={() => {
                    setCustomColor(c.value);
                    applyColor(c.value);
                  }}
                  title={c.label}
                  style={{
                    width: '28px',
                    height: '28px',
                    borderRadius: '4px',
                    border: '1px solid #d1d5db',
                    backgroundColor: c.value,
                    cursor: 'pointer',
                  }}
                />
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
              <input
                type="color"
                value={customColor}
                onChange={(e) => setCustomColor(e.target.value)}
                style={{
                  width: '28px',
                  height: '28px',
                  padding: 0,
                  border: 'none',
                  cursor: 'pointer',
                }}
              />
              <input
                type="text"
                value={customColor}
                onChange={(e) => setCustomColor(e.target.value)}
                style={{
                  flex: 1,
                  padding: '4px',
                  border: '1px solid #d1d5db',
                  borderRadius: '4px',
                  fontSize: '12px',
                  fontFamily: 'monospace',
                }}
              />
              <button
                type="button"
                onClick={() => applyColor(customColor)}
                style={{
                  padding: '4px 8px',
                  background: '#093b66',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontSize: '12px',
                }}
              >
                Apply
              </button>
            </div>
          </div>
        )}
      </div>

      <span style={{ width: '1px', background: '#d1d5db', margin: '0 0.25rem', height: '24px' }} />

      <button
        type="button"
        onClick={() => formatHeading('h2')}
        style={toolbarButtonStyle}
        title="Heading 2"
        aria-label="Heading 2"
      >
        H2
      </button>
      <button
        type="button"
        onClick={() => formatHeading('h3')}
        style={toolbarButtonStyle}
        title="Heading 3"
        aria-label="Heading 3"
      >
        H3
      </button>
      <button
        type="button"
        onClick={() => formatHeading('h4')}
        style={toolbarButtonStyle}
        title="Heading 4"
        aria-label="Heading 4"
      >
        H4
      </button>
      <button
        type="button"
        onClick={formatParagraph}
        style={toolbarButtonStyle}
        title="Normal text"
        aria-label="Normal text"
      >
        P
      </button>

      <span style={{ width: '1px', background: '#d1d5db', margin: '0 0.25rem', height: '24px' }} />

      <button
        type="button"
        onClick={() => formatAlign('left')}
        style={alignButtonStyle('left')}
        title={alignTitle('Align left')}
        aria-label="Align left"
        aria-pressed={!alignDisabled && (currentAlign === 'left' || currentAlign === '')}
        disabled={alignDisabled}
      >
        <svg
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
        >
          <line x1="3" y1="6" x2="21" y2="6" />
          <line x1="3" y1="12" x2="15" y2="12" />
          <line x1="3" y1="18" x2="18" y2="18" />
        </svg>
      </button>
      <button
        type="button"
        onClick={() => formatAlign('center')}
        style={alignButtonStyle('center')}
        title={alignTitle('Align center')}
        aria-label="Align center"
        aria-pressed={!alignDisabled && currentAlign === 'center'}
        disabled={alignDisabled}
      >
        <svg
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
        >
          <line x1="3" y1="6" x2="21" y2="6" />
          <line x1="6" y1="12" x2="18" y2="12" />
          <line x1="5" y1="18" x2="19" y2="18" />
        </svg>
      </button>
      <button
        type="button"
        onClick={() => formatAlign('right')}
        style={alignButtonStyle('right')}
        title={alignTitle('Align right')}
        aria-label="Align right"
        aria-pressed={!alignDisabled && currentAlign === 'right'}
        disabled={alignDisabled}
      >
        <svg
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
        >
          <line x1="3" y1="6" x2="21" y2="6" />
          <line x1="9" y1="12" x2="21" y2="12" />
          <line x1="6" y1="18" x2="21" y2="18" />
        </svg>
      </button>

      <span style={{ width: '1px', background: '#d1d5db', margin: '0 0.25rem', height: '24px' }} />

      <button
        type="button"
        onClick={formatBulletList}
        style={toolbarButtonStyle}
        title="Bullet List"
        aria-label="Bullet List"
      >
        UL
      </button>
      <button
        type="button"
        onClick={formatNumberedList}
        style={toolbarButtonStyle}
        title="Numbered List"
        aria-label="Numbered List"
      >
        OL
      </button>
      <button
        type="button"
        onClick={formatQuote}
        style={toolbarButtonStyle}
        title="Blockquote"
        aria-label="Blockquote"
      >
        Q
      </button>

      <span style={{ width: '1px', background: '#d1d5db', margin: '0 0.25rem', height: '24px' }} />

      <div ref={linkTriggerRef} style={{ position: 'relative' }}>
        <button
          type="button"
          onClick={() => setShowLinkPopover(!showLinkPopover)}
          style={toolbarButtonStyle}
          title="Add Link"
          aria-label="Add Link"
        >
          Link
        </button>
        {showLinkPopover && (
          <LinkInsertPopover
            editor={editor}
            onClose={() => setShowLinkPopover(false)}
            triggerRef={linkTriggerRef}
          />
        )}
      </div>

      <span style={{ width: '1px', background: '#d1d5db', margin: '0 0.25rem', height: '24px' }} />

      <input
        ref={imageInputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        style={{ display: 'none' }}
        onChange={handleImageUpload}
      />
      <div ref={imageTriggerRef} style={{ position: 'relative' }}>
        <button
          type="button"
          onClick={() => {
            if (enableMediaLibrary) {
              setShowImagePopover(!showImagePopover);
            } else {
              imageInputRef.current?.click();
            }
          }}
          style={{
            ...toolbarButtonStyle,
            opacity: isUploading ? 0.6 : 1,
          }}
          title="Insert Image"
          aria-label="Insert Image"
          disabled={isUploading}
        >
          {isUploading ? (
            '...'
          ) : (
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z" />
            </svg>
          )}
        </button>
        {showImagePopover && (
          <ImageInsertPopover
            editor={editor}
            onClose={() => setShowImagePopover(false)}
            onUploadClick={() => imageInputRef.current?.click()}
            variant="light"
            triggerRef={imageTriggerRef}
          />
        )}
      </div>

      <span style={{ width: '1px', background: '#d1d5db', margin: '0 0.25rem', height: '24px' }} />

      <button
        type="button"
        onClick={undo}
        style={toolbarButtonStyle}
        title="Undo"
        aria-label="Undo"
      >
        Undo
      </button>
      <button
        type="button"
        onClick={redo}
        style={toolbarButtonStyle}
        title="Redo"
        aria-label="Redo"
      >
        Redo
      </button>
    </div>
  );
}

export function LexicalField({ value, onChange, enableMediaLibrary }: LexicalFieldProps) {
  const editorContainerRef = useRef<HTMLDivElement>(null);
  const initialConfig = {
    namespace: 'PuckLexicalEditor',
    theme,
    onError: (error: Error) => {
      console.error('Lexical error:', error);
    },
    nodes: [HeadingNode, QuoteNode, ListNode, ListItemNode, LinkNode, AutoLinkNode, ImageNode],
  };

  const handleChange = useCallback(
    (editorState: EditorState, editor: LexicalEditor) => {
      editorState.read(() => {
        const html = $generateHtmlFromNodes(editor, null);
        onChange(html);
      });
    },
    [onChange]
  );

  return (
    <div
      ref={editorContainerRef}
      className="lexical-editor-root"
      style={{
        position: 'relative',
        border: '1px solid #d1d5db',
        borderRadius: '6px',
        overflow: 'visible',
        background: 'white',
      }}
    >
      <LexicalComposer initialConfig={initialConfig}>
        <Toolbar enableMediaLibrary={enableMediaLibrary} />
        <div
          style={{
            position: 'relative',
            minHeight: '150px',
            overflow: 'hidden',
            borderBottomLeftRadius: '6px',
            borderBottomRightRadius: '6px',
          }}
        >
          <RichTextPlugin
            contentEditable={
              <ContentEditable
                className="lexical-content-editable"
                style={{
                  outline: 'none',
                  minHeight: '150px',
                  padding: '0.75rem',
                  color: '#1f2937',
                }}
              />
            }
            placeholder={
              <div
                style={{
                  position: 'absolute',
                  top: '0.75rem',
                  left: '0.75rem',
                  color: '#9ca3af',
                  pointerEvents: 'none',
                }}
              >
                Start typing...
              </div>
            }
            ErrorBoundary={LexicalErrorBoundary}
          />
        </div>
        <HistoryPlugin />
        <ListPlugin />
        <LinkPlugin />
        <OnChangePlugin onChange={handleChange} />
        <InitialContentPlugin initialHtml={value || ''} />
        <ImagePlugin />
        <FloatingLinkEditorPlugin anchorRef={editorContainerRef} />
      </LexicalComposer>

      {/* Lexical editor styles */}
      <style>{`
        .lexical-content-editable {
          min-height: 150px;
          padding: 0.75rem;
        }
        .lexical-content-editable:focus {
          outline: none;
        }
        .lexical-paragraph {
          margin: 0 0 1em 0;
        }
        .lexical-heading-h2 {
          font-size: 1.5em;
          font-weight: 600;
          margin: 1.5em 0 0.5em 0;
        }
        .lexical-heading-h3 {
          font-size: 1.25em;
          font-weight: 600;
          margin: 1.5em 0 0.5em 0;
        }
        .lexical-heading-h4 {
          font-size: 1.125em;
          font-weight: 600;
          margin: 1.5em 0 0.5em 0;
        }
        .lexical-list-ul {
          list-style: disc;
          margin: 0 0 1em 0;
          padding-left: 1.5em;
        }
        .lexical-list-ol {
          list-style: decimal;
          margin: 0 0 1em 0;
          padding-left: 1.5em;
        }
        .lexical-list-item {
          margin: 0.25em 0;
        }
        .lexical-quote {
          border-left: 3px solid #d1d5db;
          margin: 1em 0;
          padding-left: 1em;
          color: #6b7280;
        }
        .lexical-link {
          color: var(--color-primary-accent, #38bdf8);
          text-decoration: underline;
        }
        .lexical-link:hover {
          color: #6cd2ff;
        }
        .lexical-text-bold {
          font-weight: 600;
        }
        .lexical-text-italic {
          font-style: italic;
        }
        .lexical-text-strikethrough {
          text-decoration: line-through;
        }
        .lexical-text-underline {
          text-decoration: underline;
        }
      `}</style>
    </div>
  );
}
