import React, { useEffect } from 'react';

const getLanguageMode = (filename = '') => {
  const ext = filename.split('.').pop()?.toLowerCase();
  switch (ext) {
    case 'js': case 'jsx': return 'JavaScript / React';
    case 'ts': case 'tsx': return 'TypeScript / React';
    case 'py': return 'Python';
    case 'json': return 'JSON';
    case 'html': return 'HTML';
    case 'css': return 'CSS';
    case 'sh': return 'Bash / Shell';
    case 'md': return 'Markdown';
    default: return 'Plain Text';
  }
};

export default function CodeEditor({ filename, value, onChange, onSave }) {
  const language = getLanguageMode(filename);

  useEffect(() => {
    const handleKeyDown = (e) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        if (onSave) onSave();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onSave]);

  const lineCount = (value || '').split('\n').length;
  const lineNumbers = Array.from({ length: Math.max(lineCount, 1) }, (_, i) => i + 1);

  return (
    <div className="flex flex-col h-full bg-slate-950 border border-slate-800 rounded-lg overflow-hidden font-mono text-sm">
      {/* Editor Status Bar */}
      <div className="bg-slate-900 px-4 py-2 text-xs text-slate-400 border-b border-slate-800 flex justify-between items-center select-none">
        <div className="flex items-center gap-3">
          <span className="text-slate-200 font-semibold">{filename || 'Untitled'}</span>
          <span className="bg-slate-800 px-2 py-0.5 rounded text-[10px] text-blue-400 font-medium uppercase">
            {language}
          </span>
        </div>
        <div className="flex items-center gap-4 text-[11px]">
          <span>Lines: {lineCount}</span>
          <span className="text-slate-500">Press Ctrl+S to save</span>
        </div>
      </div>

      {/* Main Textarea Area with Line Numbers */}
      <div className="flex-1 flex overflow-hidden">
        {/* Line Numbers Sidebar */}
        <div className="bg-slate-900/50 text-slate-600 px-3 py-3 select-none text-right border-r border-slate-800/60 leading-6 text-xs min-w-[2.5rem]">
          {lineNumbers.map((num) => (
            <div key={num}>{num}</div>
          ))}
        </div>

        {/* Text Input Surface */}
        <textarea
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="Start typing or select a file to edit..."
          spellCheck="false"
          className="flex-1 bg-transparent text-slate-100 p-3 outline-none resize-none leading-6 font-mono text-xs tab-4 caret-blue-500"
        />
      </div>
    </div>
  );
}
