/**
 * Selection Overlay Component
 *
 * Renders the visual lasso or rectangle selection path during drag operations.
 * Sits as an SVG layer above the canvas content, below UI overlays.
 */

'use client';

import React from 'react';
import { useAtomValue } from 'jotai';
import {
	selectionPathAtom,
	selectionRectAtom,
} from '../core/selection-path-store';
import { panAtom, zoomAtom } from '../core/viewport-store';

export interface SelectionOverlayProps {
	/** Fill color for the selection area */
	fillColor?: string;
	/** Stroke color for the selection border */
	strokeColor?: string;
	/** Stroke width in screen pixels */
	strokeWidth?: number;
}

/**
 * Renders the active selection path (lasso or rectangle).
 *
 * Place inside the Viewport's transform container so coordinates
 * align with world space. The component reads atoms directly.
 *
 * @example
 * ```tsx
 * <Canvas>
 *   <SelectionOverlay />
 * </Canvas>
 * ```
 */
export function SelectionOverlay({
	fillColor = 'rgba(99, 102, 241, 0.15)',
	strokeColor = 'rgba(99, 102, 241, 0.6)',
	strokeWidth = 1.5,
}: SelectionOverlayProps) {
	const path = useAtomValue(selectionPathAtom);
	const selectionRect = useAtomValue(selectionRectAtom);
	const pan = useAtomValue(panAtom);
	const zoom = useAtomValue(zoomAtom);

	if (!path) return null;

	// Invert the parent transform so the SVG covers the full viewport
	// in screen coordinates, then we draw in world coordinates
	const inverseTransform = `scale(${1 / zoom}) translate(${-pan.x}px, ${-pan.y}px)`;

	return (
		<svg
			style={{
				position: 'absolute',
				top: 0,
				left: 0,
				width: '100%',
				height: '100%',
				pointerEvents: 'none',
				overflow: 'visible',
				zIndex: 9998,
			}}
		>
			{path.type === 'rect' && selectionRect && (
				<rect
					x={selectionRect.x}
					y={selectionRect.y}
					width={selectionRect.width}
					height={selectionRect.height}
					fill={fillColor}
					stroke={strokeColor}
					strokeWidth={strokeWidth / zoom}
					strokeDasharray={`${4 / zoom} ${4 / zoom}`}
				/>
			)}
			{path.type === 'lasso' && path.points.length >= 2 && (
				<polygon
					points={path.points.map((p) => `${p.x},${p.y}`).join(' ')}
					fill={fillColor}
					stroke={strokeColor}
					strokeWidth={strokeWidth / zoom}
					strokeLinejoin="round"
				/>
			)}
		</svg>
	);
}
