смотри у меня первая буква печетаеться где нужна а потом в начале как это исправить

import { getAuth, onAuthStateChanged } from 'firebase/auth'
import {
	getDatabase,
	onValue,
	push,
	ref,
	remove,
	update,
} from 'firebase/database'
import { Trash2 } from 'lucide-react' // Импорт иконки удаления
import React, { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'

function Task() {
	const database = getDatabase()
	const [userTasks, setUserTasks] = useState({ description: '' })
	const [typingTimeout, setTypingTimeout] = useState(null)
	const auth = getAuth()
	const navigate = useNavigate()
	const [user, setUser] = useState(null)
	const [tasks, setTasks] = useState([]) // Store tasks for todo list
	const textareaRef = useRef(null)
	const [newTaskText, setNewTaskText] = useState('')
	const [showInput, setShowInput] = useState(false) // Toggle between button and input

	const urlParams = new URLSearchParams(window.location.search)
	const teamName = urlParams.get('teamname')
	const projectName = urlParams.get('projectname')
	const taskName = urlParams.get('taskname')
	const deadline = urlParams.get('deadline')

	// Fetch user tasks from Firebase
	const fetchUserTasks = () => {
		const todoRef = ref(
			database,
			teams/${teamName}/projects/${projectName}/tasks/${deadline}/${taskName}/todo
		)
		onValue(todoRef, snapshot => {
			if (snapshot.exists()) {
				const tasksData = snapshot.val()
				setTasks(
					Object.entries(tasksData).map(([id, task]) => ({ id, ...task }))
				)
			} else {
				setTasks([])
			}
		})

		const tasksRef = ref(
			database,
			teams/${teamName}/projects/${projectName}/tasks/${deadline}/${taskName}
		)
		onValue(tasksRef, snapshot => {
			if (snapshot.exists()) {
				const task = snapshot.val()
				setUserTasks({ description: task.description || '' })
			} else {
				setUserTasks({ description: '' })
			}
		})
	}

	const handleDescriptionChange = newDescription => {
		const taskRef = ref(
			database,
			teams/${teamName}/projects/${projectName}/tasks/${deadline}/${taskName}
		)
		update(taskRef, { description: newDescription })
	}

	const handleChange = e => {
		const newDescription = e.target.value
		setUserTasks({ description: newDescription })

		if (typingTimeout) {
			clearTimeout(typingTimeout)
		}

		const timeout = setTimeout(() => {
			handleDescriptionChange(newDescription)
		}, 1000)

		setTypingTimeout(timeout)
	}

	// Handle adding a new task
	const handleAddTask = () => {
		if (!newTaskText.trim()) {
			setShowInput(false)
			return
		}

		const newTask = {
			text: newTaskText,
			completed: false,
		}

		const tasksRef = ref(
			database,
			teams/${teamName}/projects/${projectName}/tasks/${deadline}/${taskName}/todo
		)
		push(tasksRef, newTask)
		setNewTaskText('')
		setShowInput(false)
	}

	// Handle task checkbox toggle
	const handleTaskToggle = taskId => {
		const taskRef = ref(
			database,
			teams/${teamName}/projects/${projectName}/tasks/${deadline}/${taskName}/todo/${taskId}
		)
		const task = tasks.find(t => t.id === taskId)
		update(taskRef, { completed: !task.completed })
	}

	// Handle task deletion
	const handleDeleteTask = taskId => {
		const taskRef = ref(
			database,
			teams/${teamName}/projects/${projectName}/tasks/${deadline}/${taskName}/todo/${taskId}
		)
		remove(taskRef)
	}

	// Fetch user tasks on mount
	useEffect(() => {
		onAuthStateChanged(auth, currentUser => {
			if (currentUser) {
				setUser(currentUser)
				fetchUserTasks()
			} else {
				navigate('/login')
			}
		})
	}, [auth, navigate])

	// Auto-adjust height of the textarea
	useEffect(() => {
		if (textareaRef.current) {
			textareaRef.current.style.height = 'auto'
			textareaRef.current.style.height = ${textareaRef.current.scrollHeight}px
		}
	}, [userTasks.description])
	// Сохранение позиции курсора
	const saveCursorPosition = () => {
		const selection = window.getSelection()
		if (!selection.rangeCount) return null
		const range = selection.getRangeAt(0)
		return { range }
	}

	// Восстановление позиции курсора
	const restoreCursorPosition = cursor => {
		if (!cursor || !textareaRef.current) return
		const selection = window.getSelection()
		selection.removeAllRanges()
		selection.addRange(cursor.range)
	}

	const handleInput = e => {
		const newDescription = e.target.innerText

		// Сохранить текущую позицию курсора
		const cursor = saveCursorPosition()

		// Обновить состояние с задержкой для отправки в Firebase
		setUserTasks({ description: newDescription })
		if (typingTimeout) clearTimeout(typingTimeout)
		setTypingTimeout(
			setTimeout(() => {
				// Здесь вызовите ваш метод обновления Firebase
				console.log('Save to Firebase:', newDescription)
			}, 1000)
		)

		// Восстановить курсор после обновления
		setTimeout(() => restoreCursorPosition(cursor), 0)
	}

	return (
		<div>
			<h1>Task {taskName}</h1>
			<p>Deadline: {deadline}</p>
			<div>
				<p>Description:</p>
				<div
					ref={textareaRef}
					contentEditable='true'
					onInput={handleInput}
					suppressContentEditableWarning={true}
					dangerouslySetInnerHTML={{ __html: userTasks.description }}
					style={{
						border: '1px solid #ccc',
						padding: '8px',
						minHeight: '50px',
						borderRadius: '4px',
					}}
				></div>
			</div>
			<div>
				<div>
					{tasks.map(task => (
						<div
							key={task.id}
							style={{ display: 'flex', alignItems: 'center' }}
						>
							<input
								type='checkbox'
								checked={task.completed}
								onChange={() => handleTaskToggle(task.id)}
							/>
							<span
								style={{
									textDecoration: task.completed ? 'line-through' : 'none',
									marginLeft: '8px',
								}}
							>
								{task.text}
							</span>
							<button
								onClick={e => {
									e.preventDefault()
									handleDeleteTask(task.id)
								}}
								className='p-1 hover:bg-red-50 rounded'
								title='Delete task'
							>
								<Trash2 className='h-4 w-4 text-red-500' />
							</button>
						</div>
					))}
				</div>
				{showInput ? (
					<div>
						<input
							type='text'
							value={newTaskText}
							placeholder='New Task'
							onChange={e => setNewTaskText(e.target.value)}
							onBlur={handleAddTask}
							onKeyDown={e => {
								if (e.key === 'Enter') {
									handleAddTask()
								}
							}}
						/>
					</div>
				) : (
					<button onClick={() => setShowInput(true)}>Create todolist</button>
				)}
			</div>
		</div>
	)
}

export default Task