'use client';
import { useState, useRef } from 'react';
import { trainingEvaluations, TrainingEvaluation } from './trainingModuleData';
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';

function StarRating({ value, max = 5, interactive = false, onChange }: { value: number; max?: number; interactive?: boolean; onChange?: (v: number) => void }) {
  return (
    <div className="flex items-center gap-0.5">
      {Array.from({ length: max }).map((_, i) => (
        <div key={i} className={`w-4 h-4 flex items-center justify-center ${interactive ? 'cursor-pointer' : ''}`}
          onClick={() => interactive && onChange && onChange(i + 1)}>
          <i className={`${i < value ? 'ri-star-fill' : 'ri-star-line'} text-yellow-400 text-sm`}></i>
        </div>
      ))}
      <span className="text-xs text-gray-500 ml-1">{value}/{max}</span>
    </div>
  );
}

function RatingBadge({ v }: { v: number }) {
  if (v === 0) return <span className="text-xs text-gray-400">Pending</span>;
  const colors = ['', 'bg-red-100 text-red-700', 'bg-orange-100 text-orange-700', 'bg-yellow-100 text-yellow-700', 'bg-blue-100 text-blue-700', 'bg-green-100 text-green-700'];
  return <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${colors[v] || 'bg-gray-100 text-gray-600'}`}>{v}/5</span>;
}

export default function TrainingEvaluationTab() {
  const [evals] = useState<TrainingEvaluation[]>(trainingEvaluations);
  const [selected, setSelected] = useState<TrainingEvaluation | null>(null);
  const l1Ref = useRef<HTMLDivElement>(null);
  const l2Ref = useRef<HTMLDivElement>(null);
  const l3Ref = useRef<HTMLDivElement>(null);
  const l4Ref = useRef<HTMLDivElement>(null);

  const scrollTo = (ref: React.RefObject<HTMLDivElement | null>) => {
    ref.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const completedEvals = evals.filter(e => e.l3Status === 'Completed');
  const avgL1 = evals.reduce((s, e) => s + e.l1Rating, 0) / evals.length;
  const avgGain = evals.reduce((s, e) => s + (e.l2PostScore - e.l2PreScore), 0) / evals.length;
  const l3Applied = completedEvals.filter(e => e.l3ManagerRating >= 4).length;
  const l4Improved = evals.filter(e => e.l4MetricsImproved).length;

  const l4ChartData = evals.filter(e => e.l4MetricsImproved).map(e => ({
    name: e.employeeName.split(' ')[0],
    Before: parseFloat(e.l4Before) || 0,
    After: parseFloat(e.l4After) || 0,
  }));

  const pendingL3 = evals.filter(e => e.l3Status === 'Pending');

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Avg. Satisfaction', value: `${avgL1.toFixed(1)}/5`, sub: 'Level 1 Reaction', icon: 'ri-emotion-happy-line', color: 'text-blue-600 bg-blue-50' },
          { label: 'Avg. Learning Gain', value: `+${avgGain.toFixed(0)}%`, sub: 'Level 2 Pre→Post', icon: 'ri-brain-line', color: 'text-purple-600 bg-purple-50' },
          { label: 'Behavior Applied', value: `${l3Applied}/${completedEvals.length}`, sub: 'Level 3 ≥4 rating', icon: 'ri-user-settings-line', color: 'text-orange-600 bg-orange-50' },
          { label: 'Results Improved', value: `${l4Improved}/${evals.length}`, sub: 'Level 4 KPI impact', icon: 'ri-line-chart-line', color: 'text-green-600 bg-green-50' },
        ].map(({ label, value, sub, icon, color }) => (
          <div key={label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-xl ${color} flex items-center justify-center mb-3`}>
              <i className={`${icon} text-lg`}></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="flex gap-2 flex-wrap">
        <span className="text-sm font-medium text-gray-600 mr-1 self-center">Quick Jump:</span>
        {[
          { label: 'L1 Reaction', ref: l1Ref, color: 'bg-blue-100 text-blue-700 border-blue-200' },
          { label: 'L2 Learning', ref: l2Ref, color: 'bg-purple-100 text-purple-700 border-purple-200' },
          { label: 'L3 Behavior', ref: l3Ref, color: 'bg-orange-100 text-orange-700 border-orange-200' },
          { label: 'L4 Results', ref: l4Ref, color: 'bg-green-100 text-green-700 border-green-200' },
        ].map(({ label, ref, color }) => (
          <button key={label} onClick={() => scrollTo(ref)}
            className={`px-4 py-1.5 rounded-full text-xs font-semibold border cursor-pointer hover:opacity-80 whitespace-nowrap ${color}`}>
            {label}
          </button>
        ))}
      </div>

      <div ref={l1Ref} 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 justify-between">
          <div className="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>
            <div>
              <h3 className="font-semibold text-gray-800">Level 1: Reaction</h3>
              <p className="text-xs text-gray-400">Post-training satisfaction survey results</p>
            </div>
          </div>
          <span className="text-sm font-semibold text-gray-600">{evals.length} responses</span>
        </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">Employee</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Date</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Course</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Rating (1–5 stars)</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3 max-w-[260px]">Comment</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Full Report</th>
              </tr>
            </thead>
            <tbody>
              {evals.map(e => (
                <tr key={e.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-gray-800">{e.employeeName}</p>
                    <p className="text-xs text-gray-400">{e.dept}</p>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-600">{e.evalDate}</td>
                  <td className="px-4 py-3 text-sm text-gray-700 max-w-[180px]">
                    <p className="truncate">{e.programTitle}</p>
                  </td>
                  <td className="px-4 py-3"><StarRating value={e.l1Rating} /></td>
                  <td className="px-4 py-3 text-xs text-gray-600 max-w-[260px]">
                    <p className="line-clamp-2">{e.l1Feedback}</p>
                  </td>
                  <td className="px-4 py-3">
                    <button onClick={() => setSelected(e)}
                      className="text-xs px-3 py-1.5 rounded-lg cursor-pointer font-medium text-white whitespace-nowrap hover:opacity-80"
                      style={{ background: '#b22698' }}>
                      Full Report
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div ref={l2Ref} 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 justify-between">
          <div className="flex items-center gap-3">
            <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-purple-100 text-purple-700">L2</span>
            <div>
              <h3 className="font-semibold text-gray-800">Level 2: Learning</h3>
              <p className="text-xs text-gray-400">Pre/post test scores, certificates, pass/fail status</p>
            </div>
          </div>
          <span className="text-sm font-semibold text-gray-600">Passing score: 80%</span>
        </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">Employee</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Course</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Pre %</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Post %</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Gain</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Certificate</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Status</th>
              </tr>
            </thead>
            <tbody>
              {evals.map(e => (
                <tr key={e.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-gray-800">{e.employeeName}</p>
                    <p className="text-xs text-gray-400">{e.dept}</p>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-700 max-w-[160px]">
                    <p className="truncate">{e.programTitle}</p>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-16 bg-gray-100 rounded-full h-1.5">
                        <div className="bg-gray-400 h-1.5 rounded-full" style={{ width: `${e.l2PreScore}%` }}></div>
                      </div>
                      <span className="text-xs font-semibold text-gray-600">{e.l2PreScore}%</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-16 bg-gray-100 rounded-full h-1.5">
                        <div className="h-1.5 rounded-full" style={{ width: `${e.l2PostScore}%`, background: '#b22698' }}></div>
                      </div>
                      <span className="text-xs font-semibold" style={{ color: '#b22698' }}>{e.l2PostScore}%</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-xs font-bold text-green-600">+{e.l2PostScore - e.l2PreScore}%</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${e.l2CertUploaded ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'}`}>
                      {e.l2CertUploaded ? 'Uploaded' : 'Missing'}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2.5 py-1 rounded-full text-xs font-bold ${e.l2Status === 'Pass' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                      {e.l2Status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div ref={l3Ref} className="space-y-4">
        {pendingL3.length > 0 && (
          <div className="bg-white rounded-xl shadow-sm border border-orange-100 overflow-hidden">
            <div className="px-5 py-4 border-b border-orange-100 flex items-center gap-3" style={{ background: '#fff7ed' }}>
              <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-orange-100 text-orange-700">L3</span>
              <div>
                <h3 className="font-semibold text-gray-800">Level 3: Behavior — Pending Assessments</h3>
                <p className="text-xs text-gray-500">60-day on-job application assessments awaiting manager review</p>
              </div>
              <span className="ml-auto bg-orange-100 text-orange-700 text-xs font-bold px-2.5 py-1 rounded-full">{pendingL3.length} pending</span>
            </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">Employee</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Course</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Completed</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">60-Day Due</th>
                    <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Status</th>
                  </tr>
                </thead>
                <tbody>
                  {pendingL3.map(e => {
                    const due = new Date(e.completedDate);
                    due.setDate(due.getDate() + 60);
                    return (
                      <tr key={e.id} className="border-b border-gray-50 hover:bg-gray-50">
                        <td className="px-4 py-3">
                          <p className="text-sm font-medium text-gray-800">{e.employeeName}</p>
                          <p className="text-xs text-gray-400">{e.dept}</p>
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-700">{e.programTitle}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{e.completedDate}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{due.toISOString().split('T')[0]}</td>
                        <td className="px-4 py-3">
                          <span className="px-2.5 py-1 rounded-full text-xs font-semibold bg-orange-100 text-orange-700">Awaiting Assessment</span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        <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-orange-100 text-orange-700">L3</span>
            <div>
              <h3 className="font-semibold text-gray-800">Level 3: Behavior — Completed Assessments</h3>
              <p className="text-xs text-gray-400">Manager ratings on on-job application of training</p>
            </div>
          </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">Employee</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Course</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Assessment Date</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Application</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Confidence</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Less Supervision</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Shares Learning</th>
                  <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Overall</th>
                </tr>
              </thead>
              <tbody>
                {evals.filter(e => e.l3Status === 'Completed').map(e => (
                  <tr key={e.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3">
                      <p className="text-sm font-medium text-gray-800">{e.employeeName}</p>
                      <p className="text-xs text-gray-400">{e.dept}</p>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-700 max-w-[160px]">
                      <p className="truncate">{e.programTitle}</p>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600">{e.l3AssessmentDate}</td>
                    <td className="px-4 py-3"><RatingBadge v={e.l3Application} /></td>
                    <td className="px-4 py-3"><RatingBadge v={e.l3Confidence} /></td>
                    <td className="px-4 py-3"><RatingBadge v={e.l3LessSupervision} /></td>
                    <td className="px-4 py-3"><RatingBadge v={e.l3SharesLearning} /></td>
                    <td className="px-4 py-3"><StarRating value={e.l3ManagerRating} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div ref={l4Ref} 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-green-100 text-green-700">L4</span>
          <div>
            <h3 className="font-semibold text-gray-800">Level 4: Results</h3>
            <p className="text-xs text-gray-400">KPI impact and ROI measurement</p>
          </div>
        </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">Course</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Employee</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">KPI</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Before</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">After</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">Improvement</th>
                <th className="text-left text-xs font-semibold text-gray-500 px-4 py-3">ROI</th>
              </tr>
            </thead>
            <tbody>
              {evals.map(e => (
                <tr key={e.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3 text-sm text-gray-700 max-w-[160px]">
                    <p className="truncate">{e.programTitle}</p>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-gray-800">{e.employeeName}</p>
                    <p className="text-xs text-gray-400">{e.dept}</p>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-700">{e.l4KPI}</td>
                  <td className="px-4 py-3 text-sm text-gray-600">{e.l4Before}</td>
                  <td className="px-4 py-3 text-sm font-semibold" style={{ color: e.l4MetricsImproved ? '#16a34a' : '#6b7280' }}>{e.l4After}</td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${e.l4MetricsImproved ? 'bg-green-100 text-green-700' : e.l4Improvement === 'Pending' ? 'bg-gray-100 text-gray-500' : 'bg-red-100 text-red-600'}`}>
                      {e.l4Improvement}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-bold ${e.l4ROI === 'Pending' ? 'text-gray-400' : 'text-green-600'}`}>{e.l4ROI}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {l4ChartData.length > 0 && (
          <div className="p-5 border-t border-gray-100">
            <p className="text-sm font-semibold text-gray-700 mb-3">KPI Improvement Trend (Completed Assessments)</p>
            <ResponsiveContainer width="100%" height={180}>
              <LineChart data={l4ChartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} />
                <Tooltip />
                <Line type="monotone" dataKey="Before" stroke="#9ca3af" strokeWidth={2} dot={{ r: 4 }} />
                <Line type="monotone" dataKey="After" stroke="#b22698" strokeWidth={2} dot={{ r: 4 }} />
              </LineChart>
            </ResponsiveContainer>
          </div>
        )}
      </div>

      {selected && (
        <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-2xl max-h-[90vh] overflow-y-auto">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b22698' }}>
              <div>
                <h2 className="text-white font-bold text-lg">Kirkpatrick Full Report</h2>
                <p className="text-pink-200 text-sm">{selected.employeeName} — {selected.programTitle}</p>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => {
                    const UWEZO_LOGO = 'https://storage.readdy-site.link/project_files/8353c6c3-4df0-48e3-b13e-2f6c24e6f89d/6d094512-dcbf-4464-ad6a-2cd0e9a78386_uwezo-fund-logo.png?v=507c066dfae2633b1a8385356d2c557b';
                    const style = 'body{font-family:Arial,Helvetica,sans-serif;font-size:10pt;color:#222;background:#fff;margin:0;padding:30px;}' +
                      '.page{max-width:760px;margin:0 auto;}' +
                      '.logo-row{text-align:center;margin-bottom:16px;}' +
                      '.logo-img{height:85px;}' +
                      '.doc-title{text-align:center;font-size:15pt;font-weight:bold;color:#b22698;letter-spacing:2px;text-transform:uppercase;margin-bottom:4px;}' +
                      '.divider{border:none;border-top:3px solid #b22698;margin:8px 0 18px;}' +
                      '.sub-title{text-align:center;font-size:13pt;font-weight:bold;color:#b22698;margin-bottom:20px;}' +
                      '.section{margin-bottom:18px;}' +
                      '.section-header{background:#b22698;color:#fff;font-size:10pt;font-weight:bold;padding:6px 12px;border-radius:4px 4px 0 0;text-transform:uppercase;letter-spacing:0.5px;}' +
                      '.section-body{border:1px solid #e0d0e8;border-top:none;border-radius:0 0 4px 4px;padding:12px 14px;}' +
                      'table.info{width:100%;border-collapse:collapse;}' +
                      'table.info td{padding:7px 12px;border-bottom:1px solid #ece8f0;font-size:10pt;vertical-align:top;}' +
                      'table.info td:first-child{font-weight:600;color:#555;width:38%;background:#f8f0fc;border-right:1px solid #ece8f0;}' +
                      '.footer{margin-top:30px;border-top:1px solid #eee;padding-top:12px;text-align:center;font-size:8.5pt;color:#bbb;}';

                    let html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Kirkpatrick Report - ' + selected.employeeName + '</title><style>' + style + '</style></head><body>';
                    html += '<div class="page">';
                    html += '<div class="logo-row"><img src="' + UWEZO_LOGO + '" class="logo-img" alt="Uwezo Fund Logo" /></div>';
                    html += '<div class="doc-title">UWEZO FUND OVERSIGHT BOARD</div>';
                    html += '<hr class="divider">';
                    html += '<div class="sub-title">KIRKPATRICK EVALUATION REPORT</div>';
                    html += '<div style="text-align:right;font-size:9pt;color:#666;margin-bottom:14px;"><strong>Employee:</strong> ' + selected.employeeName + ' &nbsp;|&nbsp; <strong>Course:</strong> ' + selected.programTitle + ' &nbsp;|&nbsp; <strong>Date:</strong> ' + new Date().toLocaleDateString('en-KE') + '</div>';
                    html += '<div class="section"><div class="section-header">LEVEL 1: REACTION</div>' +
                      '<div class="section-body"><table class="info">' +
                      '<tr><td>Rating</td><td>' + selected.l1Rating + '/5</td></tr>' +
                      '<tr><td>Feedback</td><td>' + selected.l1Feedback + '</td></tr>' +
                      '</table></div></div>';
                    html += '<div class="section"><div class="section-header">LEVEL 2: LEARNING</div>' +
                      '<div class="section-body"><table class="info">' +
                      '<tr><td>Pre-Test Score</td><td>' + selected.l2PreScore + '%</td></tr>' +
                      '<tr><td>Post-Test Score</td><td>' + selected.l2PostScore + '%</td></tr>' +
                      '<tr><td>Gain</td><td>+' + (selected.l2PostScore - selected.l2PreScore) + '%</td></tr>' +
                      '<tr><td>Status</td><td>' + selected.l2Status + '</td></tr>' +
                      '<tr><td>Certificate</td><td>' + (selected.l2CertUploaded ? 'Uploaded' : 'Not Uploaded') + '</td></tr>' +
                      '</table></div></div>';
                    html += '<div class="section"><div class="section-header">LEVEL 3: BEHAVIOR</div>' +
                      '<div class="section-body"><table class="info">' +
                      '<tr><td>Assessment Status</td><td>' + selected.l3Status + '</td></tr>';
                    if (selected.l3Status === 'Completed') {
                      html += '<tr><td>Application of Skills</td><td>' + selected.l3Application + '/5</td></tr>' +
                        '<tr><td>Confidence in Role</td><td>' + selected.l3Confidence + '/5</td></tr>' +
                        '<tr><td>Less Supervision Needed</td><td>' + selected.l3LessSupervision + '/5</td></tr>' +
                        '<tr><td>Shares Learning with Team</td><td>' + selected.l3SharesLearning + '/5</td></tr>' +
                        '<tr><td>Overall Manager Rating</td><td>' + selected.l3ManagerRating + '/5</td></tr>' +
                        '<tr><td>Notes</td><td>' + selected.l3Notes + '</td></tr>';
                    }
                    html += '</table></div></div>';
                    html += '<div class="section"><div class="section-header">LEVEL 4: RESULTS</div>' +
                      '<div class="section-body"><table class="info">' +
                      '<tr><td>KPI Measured</td><td>' + selected.l4KPI + '</td></tr>' +
                      '<tr><td>Before Training</td><td>' + selected.l4Before + '</td></tr>' +
                      '<tr><td>After Training</td><td>' + selected.l4After + '</td></tr>' +
                      '<tr><td>Improvement</td><td>' + selected.l4Improvement + '</td></tr>' +
                      '<tr><td>ROI</td><td>' + selected.l4ROI + '</td></tr>' +
                      '<tr><td>Notes</td><td>' + selected.l4Notes + '</td></tr>' +
                      '</table></div></div>';
                    html += '<div class="footer">Uwezo Fund HRMS v2.0.1 © 2026 &bull; P.O. Box 00100, Nairobi, Kenya</div>';
                    html += '</div></body></html>';

                    const blob = new Blob([html], { type: 'text/html' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `kirkpatrick-report-${selected.employeeName.replace(/\s+/g, '-')}.pdf.html`;
                    a.click();
                    URL.revokeObjectURL(url);
                  }}
                  className="flex items-center gap-1.5 px-3 py-1.5 bg-white/20 hover:bg-white/30 rounded-lg text-white text-xs font-medium cursor-pointer whitespace-nowrap">
                  <i className="ri-download-line"></i> Download PDF
                </button>
                <button onClick={() => setSelected(null)} 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>
            <div className="p-6 space-y-4">
              <div className="border border-blue-100 rounded-xl p-4">
                <div className="flex items-center gap-2 mb-3">
                  <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700">L1</span>
                  <h4 className="font-semibold text-gray-800 text-sm">Reaction — Post-Training Survey</h4>
                </div>
                <StarRating value={selected.l1Rating} />
                <p className="text-sm text-gray-700 mt-2 bg-gray-50 rounded-lg p-3">{selected.l1Feedback}</p>
              </div>
              <div className="border border-purple-100 rounded-xl p-4">
                <div className="flex items-center gap-2 mb-3">
                  <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-purple-100 text-purple-700">L2</span>
                  <h4 className="font-semibold text-gray-800 text-sm">Learning — Pre/Post Assessment</h4>
                </div>
                <div className="grid grid-cols-3 gap-4">
                  <div className="text-center p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-gray-400">Pre-Test</p>
                    <p className="text-xl font-bold text-gray-600">{selected.l2PreScore}%</p>
                  </div>
                  <div className="text-center p-3 bg-purple-50 rounded-lg">
                    <p className="text-xs text-gray-400">Post-Test</p>
                    <p className="text-xl font-bold" style={{ color: '#b22698' }}>{selected.l2PostScore}%</p>
                  </div>
                  <div className="text-center p-3 bg-green-50 rounded-lg">
                    <p className="text-xs text-gray-400">Gain</p>
                    <p className="text-xl font-bold text-green-600">+{selected.l2PostScore - selected.l2PreScore}%</p>
                  </div>
                </div>
                <div className="flex items-center gap-3 mt-3">
                  <span className={`px-2.5 py-1 rounded-full text-xs font-bold ${selected.l2Status === 'Pass' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>{selected.l2Status}</span>
                  <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${selected.l2CertUploaded ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-600'}`}>
                    Certificate: {selected.l2CertUploaded ? 'Uploaded' : 'Not Uploaded'}
                  </span>
                </div>
              </div>
              <div className="border border-orange-100 rounded-xl p-4">
                <div className="flex items-center gap-2 mb-3">
                  <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-orange-100 text-orange-700">L3</span>
                  <h4 className="font-semibold text-gray-800 text-sm">Behavior — 60-Day On-Job Assessment</h4>
                  <span className={`ml-auto px-2 py-0.5 rounded-full text-xs font-semibold ${selected.l3Status === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-orange-100 text-orange-700'}`}>{selected.l3Status}</span>
                </div>
                {selected.l3Status === 'Completed' ? (
                  <div className="space-y-2">
                    {[
                      ['Application of Skills', selected.l3Application],
                      ['Confidence in Role', selected.l3Confidence],
                      ['Less Supervision Needed', selected.l3LessSupervision],
                      ['Shares Learning with Team', selected.l3SharesLearning],
                    ].map(([label, val]) => (
                      <div key={String(label)} className="flex items-center justify-between">
                        <span className="text-xs text-gray-600">{label}</span>
                        <RatingBadge v={Number(val)} />
                      </div>
                    ))}
                    <div className="pt-2 border-t border-gray-100">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-xs font-semibold text-gray-700">Overall Manager Rating</span>
                        <StarRating value={selected.l3ManagerRating} />
                      </div>
                      {selected.l3Notes && <p className="text-sm text-gray-700 bg-gray-50 rounded-lg p-3">{selected.l3Notes}</p>}
                    </div>
                  </div>
                ) : (
                  <p className="text-sm text-orange-600 bg-orange-50 rounded-lg p-3">Assessment pending — 60-day window not yet reached.</p>
                )}
              </div>
              <div className="border border-green-100 rounded-xl p-4">
                <div className="flex items-center gap-2 mb-3">
                  <span className="px-2.5 py-0.5 rounded-full text-xs font-bold bg-green-100 text-green-700">L4</span>
                  <h4 className="font-semibold text-gray-800 text-sm">Results — Performance Impact</h4>
                </div>
                <div className="grid grid-cols-2 gap-3 mb-3">
                  {[
                    ['KPI Measured', selected.l4KPI],
                    ['Before Training', selected.l4Before],
                    ['After Training', selected.l4After],
                    ['Improvement', selected.l4Improvement],
                    ['ROI', selected.l4ROI],
                  ].map(([k, v]) => (
                    <div key={k} className="bg-gray-50 rounded-lg p-2.5">
                      <p className="text-xs text-gray-400">{k}</p>
                      <p className={`text-sm font-bold mt-0.5 ${k === 'Improvement' || k === 'ROI' ? 'text-green-600' : 'text-gray-800'}`}>{v}</p>
                    </div>
                  ))}
                </div>
                {selected.l4Notes && <p className="text-sm text-gray-700 bg-gray-50 rounded-lg p-3">{selected.l4Notes}</p>}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
