import React from 'react';
import ResizeHandles from './ResizeHandles';
import { useElementDrag } from './hooks/useElementDrag';
import { useElementSelection } from './hooks/useElementSelection';
import { getElementStyle } from './utils/elementUtils';
import './elements.css';

const LINE_CHARS = {
  single: '│',
  double: '║'
};

function VerticalLine({
  element,
  isSelected,
  isSingleSelection,
  onSelect,
  onDelete,
  onUpdate,
  onDragStart,
  onDrag,
  charWidth,
  charHeight,
  crossroadMap = {},
  toolMode
}) {
  const lineChar = LINE_CHARS[element.lineStyle || 'single'];

  // Use custom hooks for drag and selection
  const { isDragging, handleMouseDown: handleDragMouseDown } = useElementDrag({
    isSelected,
    onDragStart,
    onDrag,
    toolMode
  });

  const { handleClick } = useElementSelection({
    isSelected,
    onSelect,
    onDelete,
    toolMode
  });

  const handleMouseDown = (e) => {
    onSelect(e); // Select element before dragging
    handleDragMouseDown(e, element.id);
  };

  const handleResize = (updates) => {
    onUpdate(updates);
  };

  // Render line vertically with possible crossroad overrides
  const renderLine = () => {
    const lines = [];
    for (let i = 0; i < element.length; i++) {
      const gridX = element.x;
      const gridY = element.y + i;
      const crossroadKey = `${gridX},${gridY}`;

      // Use crossroad character if it exists, otherwise use line character
      const char = crossroadMap[crossroadKey] || lineChar;

      lines.push(
        <div key={i} className="vertical-line-char" style={{ height: `${charHeight}px` }}>
          {char}
        </div>
      );
    }
    return lines;
  };

  // Use element class method for style calculation
  const style = getElementStyle(element, charWidth, charHeight);

  return (
    <div
      className={`line-element vertical-line ${isSelected ? 'selected' : ''} ${isDragging ? 'dragging' : ''}`}
      style={style}
      onClick={handleClick}
      onMouseDown={handleMouseDown}
    >
      {renderLine()}
      {isSingleSelection && (
        <ResizeHandles
          element={element}
          onResize={handleResize}
          charWidth={charWidth}
          charHeight={charHeight}
        />
      )}
    </div>
  );
}

export default VerticalLine;
