"use client"

import type React from "react"
import { useEffect, useRef } from "react"

interface MarkdownInputProps {
  content: string
  onChange: (content: string) => void
  onTextareaRef: (ref: HTMLTextAreaElement | null) => void
}

export function MarkdownInput({ content, onChange, onTextareaRef }: MarkdownInputProps) {
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  useEffect(() => {
    onTextareaRef(textareaRef.current)
  }, [onTextareaRef])

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Tab") {
      e.preventDefault()
      const start = e.currentTarget.selectionStart
      const end = e.currentTarget.selectionEnd
      const newContent = content.substring(0, start) + "  " + content.substring(end)
      onChange(newContent)

      setTimeout(() => {
        if (textareaRef.current) {
          textareaRef.current.setSelectionRange(start + 2, start + 2)
        }
      }, 0)
    }
  }

  return (
    <div className="flex-1 relative bg-gradient-to-br from-white to-gray-50/50">
      <textarea
        ref={textareaRef}
        value={content}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={handleKeyDown}
        className="w-full h-full p-6 resize-none border-0 outline-none bg-transparent font-mono text-sm leading-relaxed 
                   placeholder:text-gray-400 focus:placeholder:text-gray-300 transition-all duration-200
                   selection:bg-blue-100 selection:text-blue-900"
        placeholder="✨ Start writing your markdown here... 

Try typing:
# My Amazing Title
**Bold text** and *italic text*
- List items
> Blockquotes
```code blocks```"
        spellCheck={false}
      />
      {/* Subtle grid pattern overlay */}
      <div
        className="absolute inset-0 pointer-events-none opacity-[0.02]"
        style={{
          backgroundImage: `radial-gradient(circle at 1px 1px, rgba(0,0,0,0.15) 1px, transparent 0)`,
          backgroundSize: "20px 20px",
        }}
      />
    </div>
  )
}
