/**
 * Viewport Component — v3 (Gesture System v2 integration)
 *
 * Thin rendering shell. All gesture handling is delegated to
 * useCanvasGestures via the GestureProvider context.
 */

import React, { useEffect, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { zoomAtom, panAtom, viewportRectAtom } from '../core/viewport-store';
import { useCanvasGestures } from '../gestures/useCanvasGestures';
import { useInputContext } from '../gestures/GestureProvider';
import { Grid, Crosshairs } from './Grid';

export interface ViewportProps {
	children: React.ReactNode;
	minZoom?: number;
	maxZoom?: number;
	zoomSensitivity?: number;
	className?: string;
	style?: React.CSSProperties;
	enablePan?: boolean;
	enableZoom?: boolean;
}

/**
 * Canvas viewport with pan/zoom support.
 * Touch-first: works natively with finger, Apple Pencil, and mouse.
 */
export function Viewport({
	children,
	minZoom = 0.1,
	maxZoom = 5,
	zoomSensitivity = 0.0015,
	className,
	style,
	enablePan = true,
	enableZoom = true,
}: ViewportProps) {
	const panVals = useAtomValue(panAtom);
	const zoomVal = useAtomValue(zoomAtom);
	const viewportRect = useAtomValue(viewportRectAtom);
	const viewportRef = useRef<HTMLDivElement>(null);

	// Read shared input system from InputProvider
	const { system, onAction, registerCanvasRoot } = useInputContext();

	useEffect(() => {
		registerCanvasRoot(viewportRef.current);
		return () => registerCanvasRoot(null);
	}, [registerCanvasRoot]);

	// Wire all gesture handling (pan, zoom, inertia, taps, long-press, etc.)
	useCanvasGestures({
		ref: viewportRef,
		minZoom,
		maxZoom,
		zoomSensitivity,
		enablePan,
		enableZoom,
		mappingIndex: system.mappingIndex,
		onAction,
		heldKeys: system.heldKeys,
	});

	return (
		<div
			ref={viewportRef}
			id="viewport-canvas"
			className={className}
			data-viewport="true"
			data-canvas-root="true"
			tabIndex={-1}
			style={{
				width: '100%',
				height: '100%',
				overflow: 'hidden',
				position: 'relative',
				touchAction: 'none',
				userSelect: 'none',
				WebkitUserSelect: 'none',
				WebkitTouchCallout: 'none',
				background: 'var(--canvas-bg, #23272a)',
				...style,
			}}
		>
			<div
				style={{
					transform: `translate(${panVals.x}px, ${panVals.y}px) scale(${zoomVal})`,
					transformOrigin: '0 0',
					width: '100%',
					height: '100%',
				}}
			>
				{viewportRect && viewportRect.width > 0 && viewportRect.height > 0 && (
					<>
						<Grid pan={panVals} zoom={zoomVal} viewportWidth={viewportRect.width} viewportHeight={viewportRect.height} />
						<Crosshairs pan={panVals} zoom={zoomVal} viewportWidth={viewportRect.width} viewportHeight={viewportRect.height} />
					</>
				)}
				{children}
			</div>
		</div>
	);
}
