import type { GuessEntry } from '@wordle/shared';

const COLOR_MAP: Record<string, string> = {
  g: '#6aaa64',
  y: '#c9b458',
  x: '#787c7e',
};

const CURSOR_COLOR = '#6aaa64';

interface GridProps {
  guesses: GuessEntry[];
  maxRows?: number;
  /** Cursor position in the current (unsubmitted) row (0–5) */
  cursorPos?: number;
  /** Called when the user taps a cell in the current row */
  onCursorMove?: (pos: number) => void;
}

export function Grid({ guesses, maxRows = 6, cursorPos = 0, onCursorMove }: GridProps) {
  const rows: (GuessEntry | null)[] = [...guesses];
  while (rows.length < maxRows) {
    rows.push(null);
  }

  // Find the current (unsubmitted) row — the first entry with empty colors
  // that has letters typed. Only one such row can exist.
  const currentRowIdx = rows.findIndex(
    (e) => e && e.colors.length === 0 && e.guess.length > 0,
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', alignItems: 'center' }}>
      <style>{`
        @keyframes wl-blink {
          0%, 100% { opacity: 1; }
          50% { opacity: 0; }
        }
      `}</style>
      {rows.map((entry, rowIdx) => (
        <div key={rowIdx} style={{ display: 'flex', gap: '4px' }}>
          {Array.from({ length: 5 }).map((_, colIdx) => {
            const letter = entry?.guess[colIdx] ?? '';
            const colorCode = entry?.colors?.[colIdx];
            const hasFeedback = entry ? entry.colors.length > 0 : false;
            const bg = hasFeedback && colorCode ? COLOR_MAP[colorCode] : 'transparent';
            const isCurrentRow = rowIdx === currentRowIdx;
            const showCursor = isCurrentRow && colIdx === cursorPos;

            return (
              <div
                key={colIdx}
                onClick={() => { if (isCurrentRow) onCursorMove?.(colIdx); }}
                style={{
                  width: '52px',
                  height: '52px',
                  border: `2px solid ${letter ? '#878a8c' : '#d3d6da'}`,
                  backgroundColor: bg,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '1.5rem',
                  fontWeight: 'bold',
                  color: hasFeedback ? '#fff' : '#000',
                  textTransform: 'uppercase',
                  fontFamily: 'monospace',
                  position: 'relative',
                  cursor: isCurrentRow ? 'pointer' : undefined,
                }}
              >
                {letter}
                {showCursor && (
                  <div
                    style={{
                      position: 'absolute',
                      bottom: '4px',
                      left: '8px',
                      right: '8px',
                      height: '3px',
                      backgroundColor: CURSOR_COLOR,
                      borderRadius: '1px',
                      animation: 'wl-blink 1s step-end infinite',
                    }}
                  />
                )}
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}
