/**
 * Remote Cursor Component
 * Renders remote users' cursors in the editor
 */

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

export interface RemoteCursorProps {
  getRemoteUsers: () => Map<string, RemoteUser>;
  editorRef: HTMLTextAreaElement | undefined;
  className?: string;
}

interface CursorOverlay {
  userId: string;
  userName: string;
  position: number;
  color: string;
  selection?: { anchor: number; head: number };
}

export const RemoteCursor: Component<RemoteCursorProps> = (props) => {
  const [cursors, setCursors] = createSignal<CursorOverlay[]>([]);
  const [cursorElements, setCursorElements] = createSignal<Map<string, HTMLDivElement>>(new Map());

  onMount(() => {
    const updateCursors = () => {
      const userMap = props.getRemoteUsers();
      const newCursors: CursorOverlay[] = [];

      userMap.forEach((user: RemoteUser) => {
        if (user.cursor) {
          newCursors.push({
            userId: user.userId,
            userName: user.userName,
            position: user.cursor.position,
            color: user.cursor.color,
            selection: user.selection,
          });
        }
      });

      setCursors(newCursors);
    };

    updateCursors();

    // Poll for cursor updates
    const interval = setInterval(updateCursors, 100);

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

  const getPositionCoordinates = (position: number): { top: number; left: number } => {
    if (!props.editorRef) {
      return { top: 0, left: 0 };
    }

    const text = props.editorRef.value;
    const textBeforeCursor = text.slice(0, position);
    const lines = textBeforeCursor.split('\n');
    const lineNumber = lines.length - 1;
    const columnNumber = lines[lines.length - 1].length;

    // Approximate coordinates (in production, use proper text measurement)
    const lineHeight = 21; // 1.5 * 14px font size
    const charWidth = 8.4; // Approximate monospace char width

    return {
      top: lineNumber * lineHeight + 16, // +16 for padding
      left: columnNumber * charWidth + 16, // +16 for padding
    };
  };

  return (
    <div
      class={props.className || 'remote-cursor-container'}
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        pointerEvents: 'none',
        overflow: 'hidden',
      }}
    >
      <For each={cursors()}>
        {(cursor) => {
          const coords = getPositionCoordinates(cursor.position);

          return (
            <>
              {/* Cursor caret */}
              <div
                ref={(el) => {
                  const map = new Map(cursorElements());
                  map.set(cursor.userId, el);
                  setCursorElements(map);
                }}
                style={{
                  position: 'absolute',
                  top: `${coords.top}px`,
                  left: `${coords.left}px`,
                  width: '2px',
                  height: '18px',
                  backgroundColor: cursor.color,
                  zIndex: 10,
                }}
              />

              {/* User label */}
              <div
                style={{
                  position: 'absolute',
                  top: `${coords.top - 18}px`,
                  left: `${coords.left}px`,
                  backgroundColor: cursor.color,
                  color: '#fff',
                  fontSize: '11px',
                  fontWeight: '500',
                  padding: '2px 6px',
                  borderRadius: '3px 3px 3px 0',
                  whiteSpace: 'nowrap',
                  zIndex: 11,
                }}
              >
                {cursor.userName}
              </div>

              {/* Selection highlight */}
              {cursor.selection && (
                <div
                  style={{
                    position: 'absolute',
                    top: `${coords.top}px`,
                    left: `${coords.left}px`,
                    width: `${Math.abs(cursor.selection.head - cursor.selection.anchor) * 8.4}px`,
                    height: '18px',
                    backgroundColor: `${cursor.color}30`,
                    zIndex: 9,
                  }}
                />
              )}
            </>
          );
        }}
      </For>
    </div>
  );
};

export default RemoteCursor;
