import type { EditorView } from '@codemirror/view'
import { useState, useEffect, useCallback } from 'react'
import '../styles/status-bar.css'

interface StatusBarProps {
  editorView: EditorView | null
  engineReady: boolean
  lineCount: number
}

export function StatusBar({ editorView, engineReady, lineCount }: StatusBarProps) {
  const [cursor, setCursor] = useState({ line: 1, col: 1 })
  const [selection, setSelection] = useState(0)
  const [showDedication, setShowDedication] = useState(false)

  const toggleDedication = useCallback(() => {
    setShowDedication(prev => !prev)
  }, [])

  useEffect(() => {
    if (!editorView) return

    const update = () => {
      const state = editorView.state
      const pos = state.selection.main.head
      const line = state.doc.lineAt(pos)
      setCursor({ line: line.number, col: pos - line.from + 1 })

      const sel = state.selection.main
      setSelection(Math.abs(sel.to - sel.from))
    }

    // Initial
    update()

    const handler = () => update()
    editorView.dom.addEventListener('keyup', handler)
    editorView.dom.addEventListener('mouseup', handler)

    return () => {
      editorView.dom.removeEventListener('keyup', handler)
      editorView.dom.removeEventListener('mouseup', handler)
    }
  }, [editorView])

  return (
    <div className="status-bar">
      <div className="status-bar-left">
        <span>Ln {cursor.line}, Col {cursor.col}</span>
        <span>{lineCount} lines</span>
        {selection > 0 && <span>{selection} selected</span>}
      </div>
      <div className="status-bar-right">
        <span className="status-bar-engine">
          <span className={`status-bar-dot ${engineReady ? 'ready' : 'loading'}`} />
          {engineReady ? 'Ready' : 'Loading...'}
        </span>
        <span
          className="status-bar-dedication"
          onClick={toggleDedication}
          role="button"
          tabIndex={0}
        >
          Made with <span className="status-bar-heart">♥</span> for Igor Cassel
        </span>
      </div>

      {showDedication && (
        <div className="dedication-overlay" onClick={toggleDedication}>
          <div className="dedication-card" onClick={e => e.stopPropagation()}>
            <div className="dedication-heart">♥</div>
            <h2>For Igor Cassel</h2>
            <p>
              CalcText was created in honor of my cousin Igor,
              who has always had a deep love for text editors
              and the craft of building beautiful, functional tools.
            </p>
            <p className="dedication-tagline">
              Every keystroke in this editor carries that inspiration.
            </p>
            <button className="dedication-close" onClick={toggleDedication}>
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
