'use client';

import { useAutocomplete } from "../../hooks/reactQuery.mjs";
import { AutoSizedTextArea } from "./AutoSizeTextArea.mjs";
import { useEffect, useRef, useState } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
import { useConfiguration } from "@intlayer/editor-react";

//#region src/components/TextArea/AutocompleteTextArea.tsx
/**
* Custom hook for debouncing values to prevent excessive API calls.
*
* Delays updating the returned value until the input value has stopped changing
* for the specified delay period.
*
* @param value - The value to debounce
* @param delay - Delay in milliseconds before updating the debounced value
* @returns The debounced value that only updates after the delay period
*
* @example
* ```tsx
* const [searchTerm, setSearchTerm] = useState('');
* const debouncedSearchTerm = useDebounce(searchTerm, 300);
*
* useEffect(() => {
*   if (debouncedSearchTerm) {
*     performSearch(debouncedSearchTerm);
*   }
* }, [debouncedSearchTerm]);
* ```
*/
const useDebounce = (value, delay) => {
	const [debouncedValue, setDebouncedValue] = useState(value);
	useEffect(() => {
		const timer = setTimeout(() => {
			setDebouncedValue(value);
		}, delay);
		return () => clearTimeout(timer);
	}, [value, delay]);
	return debouncedValue;
};
/**
* AutoCompleteTextarea Component
*
* An intelligent textarea that provides AI-powered autocomplete suggestions as users type,
* combining auto-sizing functionality with contextual text completion.
*
* ## Features
* - **AI-Powered Suggestions**: Context-aware autocomplete using configured AI models
* - **Debounced API Calls**: Efficient suggestion fetching with 200ms debounce
* - **Visual Suggestions**: Inline preview of suggested completions
* - **Keyboard Navigation**: Tab key to accept suggestions
* - **Context Analysis**: Uses surrounding text for better suggestions
* - **Auto-Sizing**: Inherits all AutoSizedTextArea capabilities
* - **Performance Optimized**: Smart caching and minimal re-renders
*
* ## Technical Implementation
* - **Debounce Strategy**: 200ms delay before fetching suggestions
* - **Context Window**: 5 lines before/after cursor for context
* - **Minimum Trigger**: Requires 3+ characters before suggesting
* - **Position Tracking**: Ghost layer for accurate suggestion positioning
* - **Cursor Management**: Tracks cursor position during suggestion fetch
*
* ## AI Integration
* - Uses configured AI model (OpenAI, Anthropic, etc.)
* - Sends context-aware prompts for relevant suggestions
* - Respects temperature and model settings from configuration
* - Handles API errors gracefully without interrupting user flow
*
* ## Use Cases
* - **Content Creation**: Blog posts, articles, documentation
* - **Code Comments**: Intelligent code documentation assistance
* - **Email Composition**: Professional email writing assistance
* - **Creative Writing**: Story and narrative completion
* - **Technical Documentation**: API docs, README files
* - **Social Media**: Post creation with engagement optimization
*
* @example
* ```tsx
* // Blog writing assistant
* const [blogPost, setBlogPost] = useState('');
* const [isAiEnabled, setIsAiEnabled] = useState(true);
*
* <div className="space-y-4">
*   <div className="flex items-center gap-2">
*     <Switch
*       checked={isAiEnabled}
*       onChange={setIsAiEnabled}
*     />
*     <label>AI Writing Assistant</label>
*   </div>
*
*   <AutoCompleteTextarea
*     value={blogPost}
*     onChange={(e) => setBlogPost(e.target.value)}
*     placeholder="Start writing your blog post..."
*     isActive={isAiEnabled}
*     autoSize={true}
*     maxRows={15}
*     className="min-h-[200px] font-serif text-lg leading-relaxed"
*   />
* </div>
*
* // Code documentation assistant
* <AutoCompleteTextarea
*   value={docComment}
*   onChange={handleDocChange}
*   placeholder="/** Describe this function... *\/"
*   isActive={true}
*   autoSize={true}
*   maxRows={8}
*   className="font-mono text-sm"
* />
*
* // Email composition with templates
* <AutoCompleteTextarea
*   defaultValue="Dear "
*   placeholder="AI will help complete your email..."
*   isActive={true}
*   autoSize={true}
*   maxRows={12}
*   variant={InputVariant.DEFAULT}
* />
* ```
*
* ## Accessibility
* - Ghost layer is properly hidden from screen readers
* - Maintains focus management during suggestion acceptance
* - Preserves keyboard navigation patterns
* - Respects reduced motion preferences
*/
const AutoCompleteTextarea = ({ isActive = true, suggestion: suggestionProp, ...props }) => {
	const defaultValue = String(props.value ?? props.defaultValue ?? "");
	const { mutate: autocomplete } = useAutocomplete();
	const configuration = useConfiguration();
	const [isTyped, setIsTyped] = useState(false);
	const [text, setText] = useState(defaultValue);
	const [suggestion, setSuggestion] = useState("");
	const textareaRef = useRef(null);
	const placeholderRef = useRef(null);
	const ghostLayerRef = useRef(null);
	const [suggestionPosition, setSuggestionPosition] = useState(null);
	const [cursorAtFetch, setCursorAtFetch] = useState(-1);
	const debouncedText = useDebounce(text, 200);
	useEffect(() => {
		if (typeof props.value === "undefined") return;
		setText(defaultValue);
	}, [props.value, props.defaultValue]);
	useEffect(() => {
		if (!isActive) return;
		if (!isTyped) return;
		if (debouncedText.length > 3) setSuggestion("");
		else setSuggestion("");
	}, [
		debouncedText,
		isActive,
		autocomplete,
		configuration
	]);
	useEffect(() => {
		if (!suggestion || cursorAtFetch === -1 || !placeholderRef.current || !ghostLayerRef.current) {
			setSuggestionPosition(null);
			return;
		}
		const rect = placeholderRef.current.getBoundingClientRect();
		const parentRect = ghostLayerRef.current.getBoundingClientRect();
		setSuggestionPosition({
			left: rect.left - parentRect.left,
			top: rect.top - parentRect.top
		});
	}, [
		suggestion,
		cursorAtFetch,
		text
	]);
	const acceptSuggestion = () => {
		const currentCursor = textareaRef.current?.selectionStart ?? cursorAtFetch;
		if (currentCursor !== cursorAtFetch) return;
		setText(text.slice(0, currentCursor) + suggestion + text.slice(currentCursor));
		setSuggestion("");
		setCursorAtFetch(-1);
		setTimeout(() => {
			textareaRef.current?.focus();
			const newCursorPos = currentCursor + suggestion.length;
			textareaRef.current?.setSelectionRange(newCursorPos, newCursorPos);
		}, 0);
	};
	return /* @__PURE__ */ jsxs("div", {
		className: "relative w-full",
		children: [
			/* @__PURE__ */ jsxs("div", {
				ref: ghostLayerRef,
				className: "pointer-events-none absolute inset-0 whitespace-pre-wrap break-words px-1 py-3 text-base leading-[1.45rem] md:py-1 md:text-sm md:leading-[1.23rem]",
				"aria-hidden": "true",
				children: [suggestion && cursorAtFetch !== -1 ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
					/* @__PURE__ */ jsx("span", {
						className: "align-text-top text-transparent",
						children: text.slice(0, cursorAtFetch)
					}),
					/* @__PURE__ */ jsx("span", {
						ref: placeholderRef,
						style: { visibility: "hidden" },
						"aria-hidden": "true",
						children: suggestion
					}),
					/* @__PURE__ */ jsx("span", {
						className: "align-text-top text-transparent",
						children: text.slice(cursorAtFetch)
					})
				] }) : /* @__PURE__ */ jsx("span", {
					className: "align-text-top text-transparent",
					children: text
				}), suggestionProp && /* @__PURE__ */ jsx("span", {
					className: "align-text-top text-neutral",
					children: suggestionProp
				})]
			}),
			suggestion && suggestionPosition && /* @__PURE__ */ jsx("div", {
				className: "pointer-events-none whitespace-pre-wrap break-words text-base text-neutral leading-[1.45rem] md:text-sm md:leading-[1.23rem]",
				style: {
					position: "absolute",
					left: suggestionPosition.left,
					top: suggestionPosition.top
				},
				children: suggestion
			}),
			/* @__PURE__ */ jsx(AutoSizedTextArea, {
				...props,
				ref: textareaRef,
				value: text,
				onChange: (e) => {
					setIsTyped(true);
					setText(e.target.value);
					setSuggestion("");
					props.onChange?.(e);
				},
				onKeyDown: (e) => {
					if (e.key === "Tab" && suggestion) {
						e.preventDefault();
						acceptSuggestion();
					}
					props.onKeyDown?.(e);
				},
				onSelect: (e) => {
					if (suggestion && e.target.selectionStart !== cursorAtFetch) {
						setSuggestion("");
						setCursorAtFetch(-1);
					}
					props.onSelect?.(e);
				}
			})
		]
	});
};

//#endregion
export { AutoCompleteTextarea, useDebounce };
//# sourceMappingURL=AutocompleteTextArea.mjs.map