/**
 * Alignment Guides
 *
 * Renders thin colored lines across the viewport when the dragged node
 * aligns with edges/centers of other nodes. Only visible during drag.
 */

'use client';

import React from 'react';
import { useAtomValue } from 'jotai';
import { alignmentGuidesAtom } from '../core/snap-store';
import { panAtom, zoomAtom, viewportRectAtom } from '../core/viewport-store';

const GUIDE_COLOR = 'rgba(99, 160, 255, 0.6)';

/**
 * Renders alignment guide lines in canvas world space.
 * Mount inside the Viewport transform container.
 */
export function AlignmentGuides() {
	const guides = useAtomValue(alignmentGuidesAtom);
	const pan = useAtomValue(panAtom);
	const zoom = useAtomValue(zoomAtom);
	const viewportRect = useAtomValue(viewportRectAtom);

	const hasGuides = guides.verticalGuides.length > 0 || guides.horizontalGuides.length > 0;
	if (!hasGuides || !viewportRect) return null;

	// Compute world-space viewport bounds
	const worldMinX = -pan.x / zoom;
	const worldMinY = -pan.y / zoom;
	const worldMaxX = worldMinX + viewportRect.width / zoom;
	const worldMaxY = worldMinY + viewportRect.height / zoom;

	return (
		<svg
			style={{
				position: 'absolute',
				left: 0,
				top: 0,
				width: '100%',
				height: '100%',
				pointerEvents: 'none',
				overflow: 'visible',
				zIndex: 999,
			}}
		>
			{/* Vertical guides — full-height lines at given X */}
			{guides.verticalGuides.map((x, i) => (
				<line
					key={`v-${i}`}
					x1={x}
					y1={worldMinY}
					x2={x}
					y2={worldMaxY}
					stroke={GUIDE_COLOR}
					strokeWidth={1 / zoom}
					strokeDasharray={`${4 / zoom} ${4 / zoom}`}
				/>
			))}

			{/* Horizontal guides — full-width lines at given Y */}
			{guides.horizontalGuides.map((y, i) => (
				<line
					key={`h-${i}`}
					x1={worldMinX}
					y1={y}
					x2={worldMaxX}
					y2={y}
					stroke={GUIDE_COLOR}
					strokeWidth={1 / zoom}
					strokeDasharray={`${4 / zoom} ${4 / zoom}`}
				/>
			))}
		</svg>
	);
}
