import { getMessages } from '../messages/index.js';

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

interface KeyboardProps {
  letterColors: Record<string, string | undefined>;
  onKeyPress: (key: string) => void;
  /** Disable Enter key (word incomplete or invalid) */
  enterDisabled?: boolean;
}

export function Keyboard({ letterColors, onKeyPress, enterDisabled }: KeyboardProps) {
  const m = getMessages();

  const isNavKey = (key: string) =>
    key === m.keyEnter || key === m.keyBackspace ||
    key === m.keyArrowLeft || key === m.keyArrowRight;

  function navLabel(key: string): string {
    if (key === m.keyBackspace) return m.backspaceLabel;
    if (key === m.keyArrowLeft) return m.arrowLeftLabel;
    if (key === m.keyArrowRight) return m.arrowRightLabel;
    return key.toUpperCase();
  }

  function renderRow(row: string[], rowIdx: number) {
    return (
      <div key={rowIdx} style={{ display: 'flex', gap: '4px', width: '100%', justifyContent: 'center' }}>
        {row.map((key) => {
          const isSpecial = isNavKey(key);
          const letter = isSpecial ? '' : key;
          const color = isSpecial ? undefined : letterColors[letter];
          const bg = color ? COLOR_MAP[color] : '#d3d6da';
          const fg = color ? '#fff' : '#000';
          const label = isSpecial ? navLabel(key) : key.toUpperCase();
          const flexBasis = isSpecial ? '15%' : '8%';

          // Enter key: grey out when disabled
          const isEnter = key === m.keyEnter;
          const disabled = isEnter && enterDisabled;

          return (
            <div
              key={key}
              onClick={() => {
                if (disabled) return;
                onKeyPress(key);
              }}
              style={{
                flex: `0 0 ${flexBasis}`,
                height: '42px',
                backgroundColor: disabled ? '#c8c8c8' : bg,
                color: disabled ? '#999' : fg,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: isSpecial ? '0.7rem' : '0.78rem',
                fontWeight: 'bold',
                borderRadius: '4px',
                cursor: disabled ? 'not-allowed' : 'pointer',
                userSelect: 'none',
                fontFamily: 'monospace',
                opacity: disabled ? 0.6 : 1,
              }}
            >
              {label}
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '5px', alignItems: 'center', marginTop: '12px', width: '95vw', maxWidth: '340px', margin: '12px auto 0' }}>
      {m.keyboardRows.map((row, idx) => renderRow(row, idx))}
      {renderRow([...m.navRow], m.keyboardRows.length)}
    </div>
  );
}
