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 HorizontalLine({
  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 with possible crossroad overrides
  const renderLine = () => {
    let line = '';
    for (let i = 0; i < element.length; i++) {
      const gridX = element.x + i;
      const gridY = element.y;
      const crossroadKey = `${gridX},${gridY}`;

      // Use crossroad character if it exists, otherwise use line character
      if (crossroadMap[crossroadKey]) {
        line += crossroadMap[crossroadKey];
      } else {
        line += lineChar;
      }
    }
    return line;
  };

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

  return (
    <div
      className={`line-element horizontal-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 HorizontalLine;
