'use client'

import type { EditableCell } from './overlay-reconstruction-types'
import type { WordPosition } from './usePixelWordPositions'

interface OverlayCellRendererProps {
  cell: EditableCell
  displayText: string
  edited: boolean
  wordPositions: WordPosition[] | undefined
  medianCellHeightPx: number
  fontScale: number
  globalBold: boolean
  colorValue: string
  handleTextChange: (cellId: string, newText: string) => void
  handleKeyDown: (e: React.KeyboardEvent, cellId: string) => void
  resetCell: (cellId: string) => void
}

/** Renders a single cell in the overlay -- either as pixel-positioned word spans or a fallback input. */
export function OverlayCellRenderer({
  cell,
  displayText,
  edited,
  wordPositions,
  medianCellHeightPx,
  fontScale,
  globalBold,
  colorValue,
  handleTextChange,
  handleKeyDown,
  resetCell,
}: OverlayCellRendererProps) {
  const bboxPct = cell.bboxPct
  const fontFamily = "'Liberation Sans', Arial, sans-serif"

  // Pixel-analysed: render word-groups at detected positions
  if (wordPositions && wordPositions.length > 0) {
    return (
      <>
        {wordPositions.map((wp, i) => {
          const autoFontPx = medianCellHeightPx * wp.fontRatio * fontScale
          const fs = Math.max(6, autoFontPx)

          if (wordPositions.length > 1) {
            return (
              <span
                key={`${cell.cellId}_wp_${i}`}
                className="absolute leading-none pointer-events-none select-none"
                style={{
                  left: `${wp.xPct}%`,
                  top: `${wp.yPct}%`,
                  width: `${wp.wPct}%`,
                  height: `${wp.hPct}%`,
                  fontSize: `${fs}px`,
                  fontWeight: globalBold ? 'bold' : 'normal',
                  fontFamily,
                  display: 'flex',
                  alignItems: 'center',
                  whiteSpace: 'nowrap',
                  overflow: 'visible',
                  color: colorValue,
                }}
              >
                {wp.text}
              </span>
            )
          }

          return (
            <div key={`${cell.cellId}_wp_${i}`} className="absolute group" style={{
              left: `${wp.xPct}%`,
              top: `${wp.yPct}%`,
              width: `${wp.wPct}%`,
              height: `${wp.hPct}%`,
            }}>
              <input
                id={`cell-${cell.cellId}`}
                type="text"
                value={displayText}
                onChange={(e) => handleTextChange(cell.cellId, e.target.value)}
                onKeyDown={(e) => handleKeyDown(e, cell.cellId)}
                className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
                  edited ? 'bg-green-50/30' : ''
                }`}
                style={{
                  fontSize: `${fs}px`,
                  fontWeight: globalBold ? 'bold' : 'normal',
                  fontFamily,
                  lineHeight: '1',
                  color: colorValue,
                }}
                title={`${cell.cellId} (${cell.colType})`}
              />
              <ResetButton edited={edited} cellId={cell.cellId} resetCell={resetCell} />
            </div>
          )
        })}
      </>
    )
  }

  // Fallback: no pixel data -- single input at cell bbox
  if (!cell.text) return null

  const fontSize = Math.max(6, medianCellHeightPx * fontScale)
  return (
    <div key={cell.cellId} className="absolute group" style={{
      left: `${bboxPct.x}%`,
      top: `${bboxPct.y}%`,
      width: `${bboxPct.w}%`,
      height: `${bboxPct.h}%`,
    }}>
      <input
        id={`cell-${cell.cellId}`}
        type="text"
        value={displayText}
        onChange={(e) => handleTextChange(cell.cellId, e.target.value)}
        onKeyDown={(e) => handleKeyDown(e, cell.cellId)}
        className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
          edited ? 'bg-green-50/30' : ''
        }`}
        style={{
          fontSize: `${fontSize}px`,
          fontWeight: globalBold ? 'bold' : 'normal',
          fontFamily,
          lineHeight: '1',
          color: colorValue,
        }}
        title={`${cell.cellId} (${cell.colType})`}
      />
      <ResetButton edited={edited} cellId={cell.cellId} resetCell={resetCell} />
    </div>
  )
}

function ResetButton({ edited, cellId, resetCell }: { edited: boolean; cellId: string; resetCell: (id: string) => void }) {
  if (!edited) return null
  return (
    <button
      onClick={() => resetCell(cellId)}
      className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-[9px] leading-none opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
      title="Zuruecksetzen"
    >
      &times;
    </button>
  )
}
