import React from 'react';
import IsolatedLivePreview from './IsolatedLivePreview';

interface CanvasCellProps extends React.HTMLAttributes<HTMLDivElement> {
  code: string;
  selected: boolean;
  componentType?: string;
  isPreview?: boolean;
  onClick: (e: React.MouseEvent) => void;
  onDoubleClick: (e: React.MouseEvent) => void;
  onContextMenu: (e: React.MouseEvent) => void;
  className?: string;
  style?: React.CSSProperties;
  children?: React.ReactNode; // react-grid-layout injects resize handles here
  [key: string]: any; // Forward any other props react-grid-layout injects (data-grid-id, etc.)
}

const CanvasCell = React.forwardRef<HTMLDivElement, CanvasCellProps>(
  (
    {
      code,
      selected,
      componentType,
      isPreview,
      onClick,
      onDoubleClick,
      onContextMenu,
      className,
      style,
      children,
      ...rest
    },
    ref,
  ) => {
    const isSection = componentType === 'Section';

    return (
      <div
        ref={ref}
        className={className}
        style={{
          background: isSection ? 'transparent' : '#fff',
          borderRadius: isSection ? 0 : 8,
          overflow: 'hidden',
          outline: !isPreview && selected ? '2px solid #087ea4' : 'none',
          outlineOffset: 2,
          cursor: isPreview ? 'default' : 'pointer',
          ...style,
        }}
        onClick={(e) => {
          if (isPreview) return;
          e.stopPropagation();
          onClick(e);
        }}
        onDoubleClick={(e) => {
          if (isPreview) return;
          e.stopPropagation();
          onDoubleClick(e);
        }}
        onContextMenu={(e) => {
          if (isPreview) return;
          e.preventDefault();
          e.stopPropagation();
          onContextMenu(e);
        }}
        {...rest}
      >
        <div
          style={{
            width: '100%',
            height: '100%',
            pointerEvents: isPreview ? 'auto' : 'none',
            overflow: 'hidden',
          }}
        >
          <IsolatedLivePreview code={code} />
        </div>
        {/* Resize handles injected by react-grid-layout */}
        {children}
      </div>
    );
  },
);

CanvasCell.displayName = 'CanvasCell';

export default CanvasCell;
