/**
 * Remote Cursor Component
 * Renders remote user cursors in the editor with their color and name
 */

import { Component, For, createSignal, onMount } from 'solid-js';
import { UserPresence } from '../../lib/collaboration/presence-manager';

export interface RemoteCursor {
  userId: string;
  name: string;
  color: string;
  position: number;
  selectionStart?: number | null;
  selectionEnd?: number | null;
}

export interface RemoteCursorOverlayProps {
  getConnectedUsers: () => UserPresence[];
  editorContainerRef: HTMLElement | undefined;
  className?: string;
}

export const RemoteCursorOverlay: Component<RemoteCursorOverlayProps> = (props) => {
  const [cursors, setCursors] = createSignal<RemoteCursor[]>([]);
  const [editorWidth, setEditorWidth] = createSignal<number>(0);
  const [editorHeight, setEditorHeight] = createSignal<number>(0);

  // Character width for cursor positioning (monospace font assumption)
  const CHAR_WIDTH = 8.4; // Approximate width of monospace character at 14px
  const LINE_HEIGHT = 20;

  onMount(() => {
    // Initial load
    updateCursors();
    updateEditorDimensions();

    // Poll for cursor updates
    const interval = setInterval(() => {
      updateCursors();
      updateEditorDimensions();
    }, 100);

    // Listen for resize
    if (props.editorContainerRef) {
      const resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
          setEditorWidth(entry.contentRect.width);
          setEditorHeight(entry.contentRect.height);
        }
      });
      resizeObserver.observe(props.editorContainerRef);
      
      return () => {
        resizeObserver.disconnect();
        clearInterval(interval);
      };
    }

    return () => {
      clearInterval(interval);
    };
  });

  const updateCursors = () => {
    const users = props.getConnectedUsers();
    const newCursors: RemoteCursor[] = users
      .filter(user => user.cursorPosition !== null)
      .map(user => ({
        userId: user.userId,
        name: user.name,
        color: user.color,
        position: user.cursorPosition!,
        selectionStart: user.selectionStart,
        selectionEnd: user.selectionEnd,
      }));
    
    setCursors(newCursors);
  };

  const updateEditorDimensions = () => {
    if (props.editorContainerRef) {
      setEditorWidth(props.editorContainerRef.clientWidth);
      setEditorHeight(props.editorContainerRef.clientHeight);
    }
  };

  /**
   * Convert character position to pixel coordinates
   * Assumes monospace font and calculates line/column from position
   */
  const positionToCoordinates = (position: number) => {
    const charsPerLine = Math.floor(editorWidth() / CHAR_WIDTH);
    const line = Math.floor(position / charsPerLine);
    const column = position % charsPerLine;
    
    return {
      x: column * CHAR_WIDTH,
      y: line * LINE_HEIGHT,
    };
  };

  return (
    <div
      class={props.className || 'remote-cursor-overlay'}
      style={{
        position: 'absolute',
        top: '0',
        left: '0',
        right: '0',
        bottom: '0',
        pointerEvents: 'none',
        overflow: 'hidden',
      }}
    >
      <For each={cursors()}>
        {(cursor) => {
          const coords = positionToCoordinates(cursor.position);
          
          return (
            <>
              {/* Cursor line */}
              <div
                style={{
                  position: 'absolute',
                  left: `${coords.x}px`,
                  top: `${coords.y}px`,
                  width: '2px',
                  height: `${LINE_HEIGHT - 2}px`,
                  backgroundColor: cursor.color,
                  transition: 'left 0.1s ease, top 0.1s ease',
                }}
              />
              
              {/* Cursor label */}
              <div
                style={{
                  position: 'absolute',
                  left: `${coords.x}px`,
                  top: `${coords.y - 18}px`,
                  padding: '2px 6px',
                  backgroundColor: cursor.color,
                  color: 'white',
                  fontSize: '10px',
                  fontWeight: '500',
                  borderRadius: '3px 3px 3px 0',
                  whiteSpace: 'nowrap',
                  zIndex: 10,
                }}
              >
                {cursor.name}
              </div>
              
              {/* Selection highlight (if any) */}
              {cursor.selectionStart !== null && cursor.selectionEnd !== null && cursor.selectionStart !== cursor.selectionEnd && (
                (() => {
                  const startCoords = positionToCoordinates(cursor.selectionStart);
                  const endCoords = positionToCoordinates(cursor.selectionEnd);
                  const sameLine = Math.floor(startCoords.y / LINE_HEIGHT) === Math.floor(endCoords.y / LINE_HEIGHT);
                  
                  return (
                    <div
                      style={{
                        position: 'absolute',
                        left: `${startCoords.x}px`,
                        top: `${startCoords.y}px`,
                        width: `${sameLine ? endCoords.x - startCoords.x : editorWidth() - startCoords.x}px`,
                        height: `${LINE_HEIGHT - 2}px`,
                        backgroundColor: `${cursor.color}30`,
                        transition: 'left 0.1s ease, width 0.1s ease, top 0.1s ease',
                      }}
                    />
                  );
                })()
              )}
            </>
          );
        }}
      </For>
    </div>
  );
};

export default RemoteCursorOverlay;
