/**
 * Collaborative Editor Component
 * SolidJS component for real-time screenplay editing
 */

import { Component, createEffect, onMount } from 'solid-js';
import { Doc, Text } from 'yjs';
import { useCollaborativeText } from '../../lib/collaboration/solid-bindings';

export interface CollaborativeEditorProps {
  doc: Doc;
  projectId: string;
  userId: string;
  className?: string;
  onCollaboratorJoin?: (userId: string) => void;
  onCollaboratorLeave?: (userId: string) => void;
}

export const CollaborativeEditor: Component<CollaborativeEditorProps> = (props) => {
  const text = () => props.doc.getText('main');
  const { text: textContent, handleChange } = useCollaborativeText(text());

  let textareaRef: HTMLTextAreaElement | undefined;

  onMount(() => {
    // Initialize textarea with current document content
    if (textareaRef) {
      textareaRef.value = textContent();
    }

    // Listen for document changes
    const observer = () => {
      if (textareaRef) {
        const cursorPos = textareaRef.selectionStart;
        textareaRef.value = textContent();
        // Restore cursor position
        textareaRef.setSelectionRange(cursorPos, cursorPos);
      }
    };

    text().observe(observer);

    return () => {
      text().unobserve(observer);
    };
  });

  const handleInput = (event: Event) => {
    const target = event.target as HTMLTextAreaElement;
    handleChange(target.value);
  };

  return (
    <div class={props.className || 'collaborative-editor'}>
      <textarea
        ref={textareaRef}
        onInput={handleInput}
        class="screenplay-editor"
        style={{
          width: '100%',
          height: '400px',
          fontFamily: '"Courier New", Courier, monospace',
          fontSize: '14px',
          lineHeight: '1.5',
          padding: '16px',
          border: '1px solid #ccc',
          borderRadius: '4px',
          resize: 'vertical',
        }}
      />
    </div>
  );
};

export default CollaborativeEditor;
