"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CollaborativeField = void 0;
const react_1 = __importStar(require("react"));
/**
 * Collaborative Field Component
 * Text input/textarea with cursor tracking and user presence
 */
const CollaborativeField = ({ fieldName, value, onChange, onCursorChange, cursors, placeholder, multiline = false, className = '', disabled = false }) => {
    const inputRef = (0, react_1.useRef)(null);
    const [localCursorPos, setLocalCursorPos] = (0, react_1.useState)(0);
    const [isTyping, setIsTyping] = (0, react_1.useState)(false);
    const typingTimeoutRef = (0, react_1.useRef)();
    // Handle input changes
    const handleChange = (e) => {
        onChange(e.target.value);
        // Set typing indicator
        setIsTyping(true);
        if (typingTimeoutRef.current) {
            clearTimeout(typingTimeoutRef.current);
        }
        typingTimeoutRef.current = setTimeout(() => {
            setIsTyping(false);
        }, 1000);
    };
    // Handle cursor position changes
    const handleSelectionChange = (0, react_1.useCallback)(() => {
        if (!inputRef.current)
            return;
        const start = inputRef.current.selectionStart || 0;
        const end = inputRef.current.selectionEnd || 0;
        setLocalCursorPos(start);
        if (start === end) {
            onCursorChange(start);
        }
        else {
            onCursorChange(start, { start, end });
        }
    }, [onCursorChange]);
    // Listen for selection changes
    (0, react_1.useEffect)(() => {
        const input = inputRef.current;
        if (!input)
            return;
        const events = ['click', 'keyup', 'focus'];
        events.forEach(event => {
            input.addEventListener(event, handleSelectionChange);
        });
        return () => {
            events.forEach(event => {
                input.removeEventListener(event, handleSelectionChange);
            });
        };
    }, [handleSelectionChange]);
    // Render cursor indicators
    const renderCursors = () => {
        if (!inputRef.current)
            return null;
        return cursors
            .filter(cursor => cursor.field === fieldName)
            .map((cursor) => {
            const { position, selection, color, userName, userId } = cursor;
            // Calculate cursor position in pixels
            const text = value.substring(0, position);
            const textWidth = getTextWidth(text, inputRef.current);
            return (<div key={userId} className="collaborative-field__cursor" style={{
                    left: `${textWidth}px`,
                    backgroundColor: color
                }} title={userName}>
            {selection && (<div className="collaborative-field__selection" style={{
                        width: `${getTextWidth(value.substring(selection.start, selection.end), inputRef.current)}px`,
                        backgroundColor: color,
                        opacity: 0.2
                    }}/>)}
            <div className="collaborative-field__cursor-label" style={{ backgroundColor: color }}>
              {userName}
            </div>
          </div>);
        });
    };
    // Calculate text width for cursor positioning
    const getTextWidth = (text, element) => {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        if (!context)
            return 0;
        const styles = window.getComputedStyle(element);
        context.font = `${styles.fontSize} ${styles.fontFamily}`;
        return context.measureText(text).width;
    };
    // Render active users typing in this field
    const renderTypingIndicators = () => {
        const typingUsers = cursors
            .filter(cursor => cursor.field === fieldName)
            .map(cursor => cursor.userName);
        if (typingUsers.length === 0)
            return null;
        return (<div className="collaborative-field__typing">
        {typingUsers.length === 1 && `${typingUsers[0]} is typing...`}
        {typingUsers.length === 2 && `${typingUsers.join(' and ')} are typing...`}
        {typingUsers.length > 2 && `${typingUsers.length} people are typing...`}
      </div>);
    };
    const InputComponent = multiline ? 'textarea' : 'input';
    return (<div className={`collaborative-field ${className}`}>
      <div className="collaborative-field__wrapper">
        <InputComponent ref={inputRef} className="collaborative-field__input" value={value} onChange={handleChange} placeholder={placeholder} disabled={disabled} data-field={fieldName}/>
        
        <div className="collaborative-field__cursors">
          {renderCursors()}
        </div>
      </div>
      
      {renderTypingIndicators()}
      
      <style jsx>{`
        .collaborative-field {
          position: relative;
          width: 100%;
        }
        
        .collaborative-field__wrapper {
          position: relative;
        }
        
        .collaborative-field__input {
          width: 100%;
          padding: 8px 12px;
          font-size: 14px;
          border: 1px solid #ddd;
          border-radius: 4px;
          transition: border-color 0.2s ease;
        }
        
        .collaborative-field__input:focus {
          outline: none;
          border-color: #4ECDC4;
        }
        
        .collaborative-field__input:disabled {
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
        
        textarea.collaborative-field__input {
          min-height: 100px;
          resize: vertical;
        }
        
        .collaborative-field__cursors {
          position: absolute;
          top: 0;
          left: 0;
          pointer-events: none;
          z-index: 10;
        }
        
        .collaborative-field__cursor {
          position: absolute;
          top: 8px;
          width: 2px;
          height: 20px;
          animation: blink 1s infinite;
        }
        
        @keyframes blink {
          0%, 50% { opacity: 1; }
          51%, 100% { opacity: 0; }
        }
        
        .collaborative-field__cursor-label {
          position: absolute;
          top: -20px;
          left: -2px;
          padding: 2px 4px;
          font-size: 11px;
          color: white;
          border-radius: 3px;
          white-space: nowrap;
          transform: translateX(-50%);
        }
        
        .collaborative-field__selection {
          position: absolute;
          top: 0;
          height: 20px;
        }
        
        .collaborative-field__typing {
          margin-top: 4px;
          font-size: 12px;
          color: #666;
          font-style: italic;
        }
      `}</style>
    </div>);
};
exports.CollaborativeField = CollaborativeField;
//# sourceMappingURL=CollaborativeField.js.map