'use client';
import { useState, useEffect } from 'react';
import { useAuth } from '../../../lib/authContext';
import EmployeeLayout from '../../../components/EmployeeLayout';
import { useTrainingStore } from '../../../lib/trainingStore';
import ProgramDetailModal from './ProgramDetailModal';
import ReactionSurveyModal from './ReactionSurveyModal';
import LearningDetailModal from './LearningDetailModal';

const BRAND = '#b22698';

type Tab = 'overview' | 'reaction' | 'learning' | 'records';

function StarDisplay({ value }: { value: number }) {
  return (
    <div className="flex items-center gap-0.5">
      {Array.from({ length: 5 }).map((_, i) => (
        <div key={i} className="w-4 h-4 flex items-center justify-center">
          <i className={`${i < value ? 'ri-star-fill' : 'ri-star-line'} text-yellow-400 text-xs`}></i>
        </div>
      ))}
      <span className="text-xs text-gray-500 ml-1">{value}/5</span>
    </div>
  );
}

function TrainingRequestModal({ user, onClose, onSubmit }: { user: any; onClose: () => void; onSubmit: (form: any) => void }) {
  const [form, setForm] = useState({
    courseName: '',
    provider: '',
    mode: 'Physical' as 'Physical' | 'Virtual' | 'Hybrid',
    regNo: '',
    cost: '',
    proformaFile: '',
    admissionFile: '',
    startDate: '',
    endDate: '',
    justification: '',
    outcomes: '',
    previousTraining: false,
  });

  const set = (k: string, v: any) => setForm(p => ({ ...p, [k]: v }));
  const [errors, setErrors] = useState<string[]>([]);

  const validateAllFields = () => {
    const errs: string[] = [];
    if (!form.courseName.trim()) errs.push('Course Name is required');
    if (!form.provider.trim()) errs.push('Training Provider is required');
    if (!form.mode) errs.push('Training Mode is required');
    if (!form.regNo.trim()) errs.push('Registration Number is required');
    if (!form.cost.trim() || Number(form.cost) <= 0) errs.push('Estimated Cost (KES) is required and must be greater than 0');
    if (!form.proformaFile) errs.push('Proforma Invoice (PDF) is required');
    if (!form.admissionFile) errs.push('Admission Letter (PDF) is required');
    if (!form.startDate) errs.push('Start Date is required');
    else if (form.startDate < new Date().toISOString().split('T')[0]) errs.push('Start Date cannot be in the past');
    if (!form.endDate) errs.push('End Date is required');
    else if (form.endDate <= form.startDate) errs.push('End Date must be after Start Date');
    if (!form.justification.trim()) errs.push('Justification is required');
    if (!form.outcomes.trim()) errs.push('Expected Outcomes are required');
    return errs;
  };

  const handleSubmit = () => {
    const errs = validateAllFields();
    setErrors(errs);
    if (errs.length > 0) return;
    
    const employeeEmail = user?.email || `${user?.employeeId || user?.id}@uwezo.go.ke`;
    
    onSubmit({ ...form, employeeEmail });
    setErrors([]);
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xl max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: BRAND }}>
          <h2 className="text-white font-bold text-lg">Training Request</h2>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center cursor-pointer">
            <i className="ri-close-line text-white text-xl"></i>
          </button>
        </div>
        <div className="p-6 space-y-4">
          {errors.length > 0 && (
            <div className="bg-red-50 border border-red-200 rounded-xl p-3 space-y-1">
              {errors.map((e, i) => (
                <div key={i} className="flex items-start gap-2">
                  <i className="ri-error-warning-line text-red-500 mt-0.5 flex-shrink-0"></i>
                  <p className="text-xs text-red-700">{e}</p>
                </div>
              ))}
            </div>
          )}
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Course Name <span className="text-red-500">*</span></label>
              <input value={form.courseName} onChange={e => set('courseName', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. Advanced Data Analytics" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Training Provider <span className="text-red-500">*</span></label>
              <input value={form.provider} onChange={e => set('provider', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="Provider name" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Training Mode <span className="text-red-500">*</span></label>
              <div className="flex gap-1">
                {(['Physical', 'Virtual', 'Hybrid'] as const).map(m => (
                  <button key={m} onClick={() => set('mode', m)}
                    className={`flex-1 py-1.5 rounded-lg text-xs font-medium cursor-pointer border transition-all ${form.mode === m ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200'}`}
                    style={form.mode === m ? { background: BRAND } : {}}>
                    {m}
                  </button>
                ))}
              </div>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Registration Number <span className="text-red-500">*</span></label>
              <input value={form.regNo} onChange={e => set('regNo', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="e.g. REG2024A001" />
              <p className="text-xs text-gray-400 mt-1">Must contain both letters and numbers</p>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Estimated Cost (KES) <span className="text-red-500">*</span></label>
              <input type="number" value={form.cost} onChange={e => set('cost', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" placeholder="0" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Proforma Invoice (PDF) <span className="text-red-500">*</span></label>
              <label className={`border-2 border-dashed rounded-lg p-2 text-center hover:border-pink-300 transition-colors cursor-pointer block ${!form.proformaFile ? 'border-red-200' : 'border-gray-200'}`}>
                <i className="ri-upload-cloud-line text-gray-400 text-lg"></i>
                <p className="text-xs text-gray-500">{form.proformaFile || 'Upload PDF (Required)'}</p>
                <input type="file" accept=".pdf" className="hidden" onChange={e => set('proformaFile', e.target.files?.[0]?.name || '')} />
              </label>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Admission Letter (PDF) <span className="text-red-500">*</span></label>
              <label className={`border-2 border-dashed rounded-lg p-2 text-center hover:border-pink-300 transition-colors cursor-pointer block ${!form.admissionFile ? 'border-red-200' : 'border-gray-200'}`}>
                <i className="ri-upload-cloud-line text-gray-400 text-lg"></i>
                <p className="text-xs text-gray-500">{form.admissionFile || 'Upload PDF (Required)'}</p>
                <input type="file" accept=".pdf" className="hidden" onChange={e => set('admissionFile', e.target.files?.[0]?.name || '')} />
              </label>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Start Date <span className="text-red-500">*</span></label>
              <input type="date" value={form.startDate} onChange={e => set('startDate', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">End Date <span className="text-red-500">*</span></label>
              <input type="date" value={form.endDate} onChange={e => set('endDate', e.target.value)} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none" />
            </div>
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Justification <span className="text-red-500">*</span></label>
              <textarea value={form.justification} onChange={e => set('justification', e.target.value)} rows={2} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="Why this training is needed..." />
            </div>
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Expected Outcomes <span className="text-red-500">*</span></label>
              <textarea value={form.outcomes} onChange={e => set('outcomes', e.target.value)} rows={2} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="What you expect to achieve..." />
            </div>
            <div className="col-span-2 flex items-center gap-2">
              <input type="checkbox" id="prevTraining" checked={form.previousTraining} onChange={e => set('previousTraining', e.target.checked)} className="w-4 h-4 rounded cursor-pointer" />
              <label htmlFor="prevTraining" className="text-sm text-gray-700 cursor-pointer">I have undergone previous related training</label>
            </div>
          </div>
          <button onClick={handleSubmit}
            className="w-full py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap hover:opacity-90"
            style={{ background: BRAND }}>
            Submit Training Request
          </button>
        </div>
      </div>
    </div>
  );
}

function CertUploadModal({ record, onClose, onUpload }: { record: any; onClose: () => void; onUpload: (id: string) => void }) {
  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: BRAND }}>
          <div>
            <h2 className="text-white font-bold text-lg">Upload Certificate</h2>
            <p className="text-pink-200 text-sm">{record.courseName}</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center cursor-pointer">
            <i className="ri-close-line text-white text-xl"></i>
          </button>
        </div>
        <div className="p-6 space-y-4">
          <div className="bg-blue-50 border border-blue-200 rounded-xl p-3">
            <p className="text-xs text-blue-700 font-medium">Certificate upload is required after training completion.</p>
          </div>
          <label className="border-2 border-dashed border-gray-200 rounded-xl p-6 text-center cursor-pointer hover:border-pink-300 transition-colors block">
            <i className="ri-upload-cloud-2-line text-3xl text-gray-300"></i>
            <p className="text-sm text-gray-500 mt-2">Click to upload certificate (PDF/JPG/PNG)</p>
            <input type="file" accept=".pdf,.jpg,.png" className="hidden" onChange={() => onUpload(record.id)} />
          </label>
          <button onClick={onClose} className="w-full py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
        </div>
      </div>
    </div>
  );
}

export default function EmployeeTrainingPage() {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState<Tab>('overview');
  const [showRequest, setShowRequest] = useState(false);
  const [uploadRecord, setUploadRecord] = useState<any>(null);
  const [toast, setToast] = useState('');
  const { trainingReqs, updateTrainingReqs } = useTrainingStore();
  
  const [myTrainingRecords, setMyTrainingRecords] = useState<any[]>([]);
  const [myTrainingEvals, setMyTrainingEvals] = useState<any[]>([]);
  const [availablePrograms, setAvailablePrograms] = useState<any[]>([]);
  const [myEnrollments, setMyEnrollments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [viewProgram, setViewProgram] = useState<any>(null);
  const [reactProgram, setReactProgram] = useState<any>(null);
  const [viewLearning, setViewLearning] = useState<any>(null);

  const empId = user?.employeeId || user?.id || 'UF001';

  const fetchData = async () => {
    setLoading(true);
    try {
      const recordsRes = await fetch(`/api/training/records?employeeId=${empId}`);
      if (recordsRes.ok) {
        const records = await recordsRes.json();
        setMyTrainingRecords(records);
      }

      const evalsRes = await fetch(`/api/training/evaluations?employeeId=${empId}`);
      if (evalsRes.ok) {
        const evals = await evalsRes.json();
        setMyTrainingEvals(evals);
      }

      const programsRes = await fetch('/api/training/programs');
      if (programsRes.ok) {
        const programs = await programsRes.json();
        setAvailablePrograms(programs);
      }

      const enrollmentsRes = await fetch(`/api/training/enrollments?employeeId=${empId}`);
      if (enrollmentsRes.ok) {
        const enrollments = await enrollmentsRes.json();
        setMyEnrollments(enrollments);
      }
    } catch (error) {
      console.error('Error fetching training data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (user) {
      fetchData();
    }
  }, [user, empId]);

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3000); };

  const myEnrolled = availablePrograms.filter(p => 
    myEnrollments.some(e => e.programId === p.id)
  );

  const completedPrograms = myEnrolled.filter(p => p.status === 'Completed');
  const ongoingPrograms = myEnrolled.filter(p => p.status === 'Ongoing');
  const upcomingPrograms = myEnrolled.filter(p => p.status === 'Upcoming');

  const avgSatisfaction = myTrainingEvals.length > 0 
    ? (myTrainingEvals.reduce((s, e) => s + (e.l1Rating || 0), 0) / myTrainingEvals.length).toFixed(1) 
    : 'N/A';
  
  const avgGain = myTrainingEvals.length > 0 
    ? Math.round(myTrainingEvals.reduce((s, e) => s + ((e.l2PostScore || 0) - (e.l2PreScore || 0)), 0) / myTrainingEvals.length) 
    : 0;
  
  const missingCerts = myTrainingRecords.filter(r => r.certStatus !== 'Submitted').length;

  const handleCertUpload = (id: string) => {
    fetch(`/api/training/records/id/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ certStatus: 'Submitted', certUploadDate: new Date().toISOString().split('T')[0] })
    }).then(() => {
      setMyTrainingRecords(prev => prev.map(r => r.id === id ? { ...r, certStatus: 'Submitted', certUploadDate: new Date().toISOString().split('T')[0] } : r));
      setUploadRecord(null);
      showToast('Certificate uploaded successfully!');
    }).catch(console.error);
  };

  const handleReactionSubmit = async (data: any) => {
    try {
      const response = await fetch('/api/training/evaluations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          programId: data.programId,
          programTitle: data.programTitle,
          employeeId: empId,
          employeeName: user?.name || 'Employee',
          dept: user?.dept || 'HR',
          evalDate: data.date,
          l1Rating: data.overallRating,
          l1Feedback: data.overallComment || 'No additional comments.',
          l2PreScore: 60,
          l2PostScore: Math.min(100, 60 + data.overallRating * 6),
          l2Status: data.overallRating >= 3 ? 'Pass' : 'Fail',
        })
      });
      
      if (response.ok) {
        const newEval = await response.json();
        setMyTrainingEvals(prev => [newEval, ...prev]);
        setReactProgram(null);
        showToast('Reaction submitted! Your feedback has been recorded.');
        fetchData();
      }
    } catch (error) {
      console.error('Error submitting reaction:', error);
    }
  };

  const statusColor = (s: string) => s === 'Completed' ? '#16a34a' : s === 'Ongoing' ? '#2563eb' : '#d97706';
  const statusBg = (s: string) => s === 'Completed' ? '#dcfce7' : s === 'Ongoing' ? '#dbeafe' : '#fef3c7';

  if (loading) {
    return (
      <EmployeeLayout title="Training & Development">
        <div className="flex justify-center items-center h-64">
          <div className="w-8 h-8 border-2 border-pink-300 border-t-pink-600 rounded-full animate-spin"></div>
        </div>
      </EmployeeLayout>
    );
  }

  const TABS: { id: Tab; label: string; icon: string }[] = [
    { id: 'overview', label: 'Overview', icon: 'ri-dashboard-line' },
    { id: 'reaction', label: 'My Reaction', icon: 'ri-emotion-happy-line' },
    { id: 'learning', label: 'My Learning', icon: 'ri-brain-line' },
    { id: 'records', label: 'Training Records', icon: 'ri-history-line' },
  ];

  return (
    <EmployeeLayout title="Training & Development">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg text-sm font-medium">{toast}</div>
      )}

      <div className="flex items-center justify-between mb-5">
        <div>
          <h2 className="text-lg font-bold text-gray-800">My Training & Development</h2>
          <p className="text-sm text-gray-500">Personal training records, evaluations, and development plans</p>
        </div>
        <div className="flex items-center gap-2">
          {missingCerts > 0 && (
            <button onClick={() => setActiveTab('records')}
              className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap border border-orange-200 text-orange-600 bg-orange-50">
              <i className="ri-history-line"></i> {missingCerts} pending cert(s)
            </button>
          )}
          <button onClick={() => setShowRequest(true)}
            className="flex items-center gap-2 text-white px-4 py-2 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap hover:opacity-90 hover:shadow-md transition-all"
            style={{ background: BRAND }}>
            <i className="ri-add-line"></i> Request Training
          </button>
        </div>
      </div>

      {missingCerts > 0 && (
        <div className="mb-4 bg-orange-50 border border-orange-200 rounded-xl px-4 py-3 flex items-center gap-3">
          <i className="ri-alarm-warning-line text-orange-600"></i>
          <p className="text-sm text-orange-700 font-medium">You have {missingCerts} training certificate(s) pending upload.</p>
          <button onClick={() => setActiveTab('records')} className="ml-auto text-xs text-orange-600 font-semibold cursor-pointer whitespace-nowrap hover:underline">Upload Now</button>
        </div>
      )}

      <div className="grid grid-cols-4 gap-4 mb-5">
        {[
          { label: 'My Satisfaction', value: avgSatisfaction === 'N/A' ? 'N/A' : `${avgSatisfaction}/5`, sub: 'Avg. reaction rating', icon: 'ri-emotion-happy-line', color: '#3b82f6' },
          { label: 'My Learning Gain', value: myTrainingEvals.length > 0 ? `+${avgGain}%` : 'N/A', sub: 'Pre→Post avg gain', icon: 'ri-brain-line', color: '#8b5cf6' },
          { label: 'Programs Completed', value: completedPrograms.length, sub: 'Total completed', icon: 'ri-checkbox-circle-line', color: '#22c55e' },
          { label: 'Pending Certs', value: missingCerts, sub: 'Certificates to upload', icon: 'ri-file-warning-line', color: '#f59e0b' },
        ].map(({ label, value, sub, icon, color }) => (
          <div key={label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100 hover:shadow-md hover:-translate-y-0.5 transition-all duration-300">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center mb-3" style={{ background: color + '20' }}>
              <i className={`${icon} text-lg`} style={{ color }}></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{value}</p>
            <p className="text-sm font-medium text-gray-700 mt-0.5">{label}</p>
            <p className="text-xs text-gray-400">{sub}</p>
          </div>
        ))}
      </div>

      <div className="mb-5 overflow-x-auto">
        <div className="flex gap-1 bg-white rounded-xl shadow-sm border border-gray-100 p-1 min-w-max">
          {TABS.map(t => (
            <button key={t.id} onClick={() => setActiveTab(t.id)}
              className={`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${activeTab === t.id ? 'text-white shadow-sm' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'}`}
              style={activeTab === t.id ? { background: BRAND } : {}}>
              <div className="w-4 h-4 flex items-center justify-center">
                <i className={`${t.icon} text-xs`}></i>
              </div>
              {t.label}
              {t.id === 'records' && missingCerts > 0 && (
                <span className="ml-1 bg-orange-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center font-bold">{missingCerts}</span>
              )}
            </button>
          ))}
        </div>
      </div>

      {activeTab === 'overview' && (
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-5">
            <h3 className="font-semibold text-gray-800 mb-3">My Training Requests</h3>
            {trainingReqs.filter(r => r.employeeId === empId).length === 0 ? (
              <p className="text-sm text-gray-500">No training requests yet. Use "Request Training" to submit one.</p>
            ) : (
              <div className="space-y-3">
                {trainingReqs.filter(r => r.employeeId === empId).map(req => (
                  <div key={req.id} className="border border-gray-100 rounded-xl p-4 flex flex-wrap items-start justify-between gap-3">
                    <div>
                      <p className="font-semibold text-gray-800 text-sm">{req.courseRequested}</p>
                      <p className="text-xs text-gray-500 mt-1">Submitted {req.dateSubmitted}</p>
                      <p className="text-xs text-gray-400 mt-1">KES {req.estimatedCost?.toLocaleString()}</p>
                    </div>
                    <span className="text-xs font-semibold px-3 py-1 rounded-full bg-yellow-100 text-yellow-700">
                      Pending ({req.currentStage})
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {completedPrograms.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <div className="w-3 h-3 rounded-full bg-green-500"></div>
                <h3 className="font-semibold text-gray-800">Completed Programs ({completedPrograms.length})</h3>
              </div>
              <div className="grid grid-cols-2 gap-4">
                {completedPrograms.map(p => (
                  <div key={p.id} className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 cursor-pointer hover:shadow-md hover:-translate-y-0.5 transition-all duration-300"
                    onClick={() => setViewProgram(p)}>
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1 pr-2">
                        <h4 className="font-semibold text-gray-800 text-sm leading-tight">{p.title}</h4>
                        <p className="text-xs text-gray-400 mt-0.5">{p.dept}</p>
                      </div>
                      <span className="px-2 py-0.5 rounded-full text-xs font-bold flex-shrink-0" style={{ background: statusBg(p.status), color: statusColor(p.status) }}>
                        {p.status}
                      </span>
                    </div>
                    <div className="space-y-1.5 mb-3">
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <i className="ri-user-line"></i>
                        <span>{p.trainer}</span>
                      </div>
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <i className="ri-calendar-line"></i>
                        <span>{p.startDate ? new Date(p.startDate).toLocaleDateString() : 'TBD'} → {p.endDate ? new Date(p.endDate).toLocaleDateString() : 'TBD'}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {ongoingPrograms.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <div className="w-3 h-3 rounded-full bg-blue-500"></div>
                <h3 className="font-semibold text-gray-800">Ongoing Programs ({ongoingPrograms.length})</h3>
              </div>
              <div className="grid grid-cols-2 gap-4">
                {ongoingPrograms.map(p => (
                  <div key={p.id} className="bg-white rounded-xl border border-blue-100 shadow-sm p-4 cursor-pointer hover:shadow-md hover:-translate-y-0.5 transition-all duration-300"
                    onClick={() => setViewProgram(p)}>
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1 pr-2">
                        <h4 className="font-semibold text-gray-800 text-sm leading-tight">{p.title}</h4>
                        <p className="text-xs text-gray-400 mt-0.5">{p.dept}</p>
                      </div>
                      <span className="px-2 py-0.5 rounded-full text-xs font-bold flex-shrink-0" style={{ background: statusBg(p.status), color: statusColor(p.status) }}>
                        {p.status}
                      </span>
                    </div>
                    <div className="space-y-1.5 mb-3">
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <i className="ri-user-line"></i>
                        <span>{p.trainer}</span>
                      </div>
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <i className="ri-calendar-line"></i>
                        <span>{p.startDate ? new Date(p.startDate).toLocaleDateString() : 'TBD'} → {p.endDate ? new Date(p.endDate).toLocaleDateString() : 'TBD'}</span>
                      </div>
                    </div>
                    <div className="flex items-center justify-between pt-2 border-t border-gray-50">
                      <span className="text-xs text-gray-400">In Progress</span>
                      <span className="text-xs text-blue-600 font-medium">Ongoing</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {upcomingPrograms.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <div className="w-3 h-3 rounded-full bg-amber-500"></div>
                <h3 className="font-semibold text-gray-800">Upcoming Programs ({upcomingPrograms.length})</h3>
              </div>
              <div className="grid grid-cols-2 gap-4">
                {upcomingPrograms.map(p => (
                  <div key={p.id} className="bg-white rounded-xl border border-amber-100 shadow-sm p-4 cursor-pointer hover:shadow-md hover:-translate-y-0.5 transition-all duration-300"
                    onClick={() => setViewProgram(p)}>
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1 pr-2">
                        <h4 className="font-semibold text-gray-800 text-sm leading-tight">{p.title}</h4>
                        <p className="text-xs text-gray-400 mt-0.5">{p.dept}</p>
                      </div>
                      <span className="px-2 py-0.5 rounded-full text-xs font-bold flex-shrink-0" style={{ background: statusBg(p.status), color: statusColor(p.status) }}>
                        {p.status}
                      </span>
                    </div>
                    <div className="space-y-1.5 mb-3">
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <i className="ri-user-line"></i>
                        <span>{p.trainer}</span>
                      </div>
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <i className="ri-calendar-line"></i>
                        <span>{p.startDate ? new Date(p.startDate).toLocaleDateString() : 'TBD'} → {p.endDate ? new Date(p.endDate).toLocaleDateString() : 'TBD'}</span>
                      </div>
                    </div>
                    <div className="flex items-center justify-between pt-2 border-t border-gray-50">
                      <span className="text-xs text-gray-400">Coming Soon</span>
                      <span className="text-xs text-amber-600 font-medium">Upcoming</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {myEnrolled.length === 0 && (
            <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-12 text-center">
              <i className="ri-book-open-line text-4xl text-gray-300 mb-3 block"></i>
              <p className="text-gray-400">You are not enrolled in any programs yet</p>
            </div>
          )}
        </div>
      )}

      {activeTab === 'reaction' && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100 flex items-center gap-3">
            <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700">L1</span>
            <h3 className="font-semibold text-gray-800">My Reaction Surveys</h3>
            <span className="text-xs text-gray-400 ml-auto">{myTrainingEvals.length} records</span>
          </div>
          {myTrainingEvals.length === 0 ? (
            <div className="text-center py-12 text-gray-400 text-sm">
              <i className="ri-emotion-happy-line text-3xl block mb-2"></i>
              <p>No reaction surveys yet.</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Course</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Date</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Rating</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Comment</th>
                  </tr>
                </thead>
                <tbody>
                  {myTrainingEvals.map(e => (
                    <tr key={e.id} className="border-b border-gray-50 hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm font-medium text-gray-800">{e.programTitle}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{e.evalDate}</td>
                      <td className="px-4 py-3"><StarDisplay value={e.l1Rating || 0} /></td>
                      <td className="px-4 py-3 text-xs text-gray-600 max-w-[300px]">
                        <p className="line-clamp-2">{e.l1Feedback}</p>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {activeTab === 'records' && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100">
            <h3 className="font-semibold text-gray-800">My Training Records</h3>
            <p className="text-xs text-gray-400 mt-0.5">Upload certificates after training completion. Required within 7 days.</p>
          </div>
          {myTrainingRecords.length === 0 ? (
            <div className="text-center py-12 text-gray-400 text-sm">No training records found</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Course</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Provider</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Completed</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Hours</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Certificate</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {myTrainingRecords.map(r => (
                    <tr key={r.id} className={`border-b border-gray-50 hover:bg-gray-50 transition-colors ${r.certStatus === 'Missing' ? 'bg-red-50/30' : ''}`}>
                      <td className="px-4 py-3 text-sm font-medium text-gray-800">{r.courseName}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{r.provider}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{r.completionDate}</td>
                      <td className="px-4 py-3 text-sm font-semibold text-gray-800">{r.hoursAwarded}h</td>
                      <td className="px-4 py-3">
                        <span className={`px-2.5 py-1 rounded-full text-xs font-semibold ${r.certStatus === 'Submitted' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                          {r.certStatus}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        {r.certStatus !== 'Submitted' && (
                          <button onClick={() => setUploadRecord(r)}
                            className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg cursor-pointer font-medium text-white whitespace-nowrap hover:opacity-90"
                            style={{ background: BRAND }}>
                            <i className="ri-upload-line"></i> Upload
                          </button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {showRequest && (
        <TrainingRequestModal
          user={user}
          onClose={() => setShowRequest(false)}
          onSubmit={async (form) => {
            try {
              const response = await fetch('/api/training/requests', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  employeeId: empId,
                  employeeEmail: form.employeeEmail,
                  employeeName: user?.name || 'Employee',
                  dept: user?.dept || 'General',
                  courseRequested: form.courseName,
                  justification: form.justification,
                  trainingProvider: form.provider,
                  trainingMode: form.mode,
                  regNo: form.regNo,
                  estimatedCost: Number(form.cost) || 0,
                  proformaInvoice: form.proformaFile,
                  admissionLetter: form.admissionFile,
                  preferredStartDate: form.startDate,
                  preferredEndDate: form.endDate,
                  expectedOutcomes: form.outcomes,
                  previousTraining: form.previousTraining,
                  dateSubmitted: new Date().toISOString().split('T')[0],
                })
              });
              
              if (response.ok) {
                const newReq = await response.json();
                updateTrainingReqs(prev => [newReq, ...prev]);
                setShowRequest(false);
                showToast('Training request submitted! You can track approval status below.');
              } else {
                throw new Error('Failed to submit');
              }
            } catch (error) {
              console.error('Error submitting training request:', error);
              showToast('Failed to submit training request. Please try again.');
            }
          }}
        />
      )}

      {uploadRecord && (
        <CertUploadModal
          record={uploadRecord}
          onClose={() => setUploadRecord(null)}
          onUpload={handleCertUpload}
        />
      )}

      {viewProgram && (
        <ProgramDetailModal
          program={viewProgram}
          completionStatus={viewProgram.status}
          onClose={() => setViewProgram(null)}
          onReact={(id) => {
            const p = availablePrograms.find(prog => prog.id === id);
            if (p) { setViewProgram(null); setReactProgram(p); }
          }}
          hasReacted={myTrainingEvals.some(e => e.programId === viewProgram.id)}
        />
      )}

      {reactProgram && (
        <ReactionSurveyModal
          program={reactProgram}
          employeeName={user?.name || 'Employee'}
          onClose={() => setReactProgram(null)}
          onSubmit={handleReactionSubmit}
        />
      )}

      {viewLearning && (
        <LearningDetailModal
          evaluation={viewLearning}
          onClose={() => setViewLearning(null)}
        />
      )}
    </EmployeeLayout>
  );
}