'use client';

// @design-system: primitives/RichTextEditor
// Registered at /design-system#richtexteditor-primitive

import { useEditor, useEditorState, EditorContent } from '@tiptap/react';
import { Bold } from '@tiptap/extension-bold';
import { Italic } from '@tiptap/extension-italic';
import { Heading } from '@tiptap/extension-heading';
import { BulletList } from '@tiptap/extension-bullet-list';
import { ListItem } from '@tiptap/extension-list-item';
import { Document } from '@tiptap/extension-document';
import { Paragraph } from '@tiptap/extension-paragraph';
import { Text } from '@tiptap/extension-text';
import { History } from '@tiptap/extension-history';
import { useT } from '@/lib/i18n/react';
import { TextDirection } from 'tiptap-text-direction';

// Only the 9 extensions the toolbar actually uses — drops StarterKit's unused
// Strike, Code, CodeBlock, HorizontalRule, OrderedList, Blockquote, HardBreak,
// Dropcursor, Gapcursor from the client bundle (~25 KB gzipped saved).
const EDITOR_EXTENSIONS = [
  Document,
  Paragraph,
  Text,
  History,
  Bold,
  Italic,
  Heading.configure({ levels: [2] }),
  BulletList,
  ListItem,
  TextDirection.configure({ types: ['heading', 'paragraph'] }),
];

/** Props for the RichTextEditor component */
export interface RichTextEditorProps {
  /** Current HTML value */
  value: string;
  /** Callback fired with new HTML on every editor update */
  onChange: (html: string) => void;
  /** Text direction for the editor content */
  dir?: 'ltr' | 'rtl';
  /** Accessible label for the editor region */
  'aria-label'?: string;
}

/**
 * Multideal RichTextEditor primitive.
 *
 * Wraps Tiptap with a minimal toolbar (Bold, Italic, H2, Bullet list).
 * Supports RTL via `tiptap-text-direction`. Used in page-organizer ConfigEditors.
 *
 * @example
 * ```tsx
 * <RichTextEditor
 *   value={config.body.he}
 *   onChange={(html) => onChange({ ...config, body: { ...config.body, he: html } })}
 *   dir="rtl"
 *   aria-label={t('rich_text_he')}
 * />
 * ```
 */
export function RichTextEditor({
  value,
  onChange,
  dir = 'rtl',
  'aria-label': ariaLabel,
}: RichTextEditorProps) {
  const tRte = useT('rich_text_editor');
  const editor = useEditor({
    extensions: EDITOR_EXTENSIONS,
    enableCoreExtensions: { textDirection: false },
    content: value,
    onUpdate: ({ editor }) => onChange(editor.getHTML()),
    editorProps: {
      attributes: {
        class:
          'rte-content min-h-50 max-w-none focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-primary-500 focus-visible:ring-inset px-3 py-2 [&_h2]:text-xl [&_h2]:font-semibold [&_h2]:my-2 [&_h2]:text-text-primary [&_p]:my-1 [&_ul]:list-disc [&_ul]:ps-6 [&_ul]:my-2 [&_li]:my-0.5',
        dir,
        role: 'textbox',
        'aria-multiline': 'true',
        ...(ariaLabel ? { 'aria-label': ariaLabel } : {}),
      },
    },
  });

  const btnBase =
    'rounded px-2 py-1 text-sm transition-colors text-text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-primary-500 aria-pressed:bg-brand-primary-100 aria-pressed:text-brand-primary-700 aria-pressed:font-semibold';

  const toolbarState = useEditorState({
    editor,
    selector: ({ editor }) => ({
      isBold: editor?.isActive('bold') ?? false,
      isItalic: editor?.isActive('italic') ?? false,
      isH2: editor?.isActive('heading', { level: 2 }) ?? false,
      isBullet: editor?.isActive('bulletList') ?? false,
    }),
  });
  const isBold = toolbarState?.isBold ?? false;
  const isItalic = toolbarState?.isItalic ?? false;
  const isH2 = toolbarState?.isH2 ?? false;
  const isBullet = toolbarState?.isBullet ?? false;

  return (
    <div className="bg-surface-base border-border-default overflow-hidden rounded-md border">
      <div
        className="border-border-subtle bg-surface-raised flex gap-1 border-b px-2 py-1"
        role="toolbar"
        aria-label={tRte('aria_formatting')}
      >
        <button
          type="button"
          aria-label={tRte('aria_bold')}
          aria-pressed={isBold}
          onClick={() => editor?.chain().focus().toggleBold().run()}
          className={`${btnBase} font-bold`}
        >
          B
        </button>
        <button
          type="button"
          aria-label={tRte('aria_italic')}
          aria-pressed={isItalic}
          onClick={() => editor?.chain().focus().toggleItalic().run()}
          className={`${btnBase} italic`}
        >
          I
        </button>
        <button
          type="button"
          aria-label={tRte('aria_heading_2')}
          aria-pressed={isH2}
          onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()}
          className={btnBase}
        >
          H2
        </button>
        <button
          type="button"
          aria-label={tRte('aria_bullet_list')}
          aria-pressed={isBullet}
          onClick={() => editor?.chain().focus().toggleBulletList().run()}
          className={btnBase}
        >
          •
        </button>
      </div>
      <EditorContent editor={editor} />
    </div>
  );
}
