'use client';
import { useState } from 'react';
import { initialAppraisals, initialPIPs, PIP, RATING_LABELS, ALL_EMPLOYEES } from './performanceData';
import { motion } from 'framer-motion';

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 statusColors: Record<string, string> = {
  Active: 'bg-yellow-100 text-yellow-700',
  Successful: 'bg-green-100 text-green-700',
  Extended: 'bg-blue-100 text-blue-700',
  Terminated: 'bg-red-100 text-red-700',
};

function downloadPIPPdf(pip: PIP) {
  const style = 'body{font-family:Arial,sans-serif;padding:30px;color:#333;background:#fff;}' +
    '.page{max-width:700px;margin:0 auto;padding:20px;border:1px solid #ccc;}' +
    '.header{display:flex;justify-content:center;margin-bottom:10px;}' +
    '.logo-img{height:70px;width:auto;object-fit:contain;}' +
    '.org-name{text-align:center;font-size:14pt;font-weight:bold;color:#111;letter-spacing:2px;margin-bottom:2px;}' +
    '.org-sub{text-align:center;font-size:9pt;color:#555;margin-bottom:2px;}' +
    '.org-addr{text-align:center;font-size:8pt;color:#666;line-height:1.5;margin-bottom:8px;}' +
    '.thick-line{border:none;border-top:2px solid #111;margin:8px 0;}' +
    '.doc-title{text-align:center;font-size:11pt;font-weight:bold;color:#111;text-transform:uppercase;margin:10px 0 8px;}' +
    '.section{margin-bottom:16px;}' +
    '.section-title{color:#b22698;font-weight:bold;font-size:10pt;border-bottom:1px solid #eee;padding-bottom:4px;margin-bottom:8px;}' +
    '.table{width:100%;border-collapse:collapse;margin:8px 0;font-size:9.5pt;}' +
    '.table td{padding:6px 10px;border:1px solid #ddd;}' +
    '.table td:first-child{background:#f9f9f9;font-weight:600;width:35%;}' +
    'ol{margin:5px 0;padding-left:20px;}' +
    'ol li{margin-bottom:4px;font-size:9.5pt;}' +
    '.badge{display:inline-block;background:#22c55e;color:#fff;padding:5px 14px;border-radius:3px;font-size:10pt;font-weight:bold;}' +
    '.signature-area{margin-top:30px;display:flex;justify-content:space-between;}' +
    '.signature-box{width:45%;}' +
    '.signature-line{border-top:1px solid #333;margin-top:40px;padding-top:4px;font-size:9pt;}' +
    '.footer-bar{background:#b22698;color:#fff;text-align:center;padding:8px 12px;font-size:8pt;font-weight:bold;margin-top:15px;}' +
    '.footer-bar span{margin:0 8px;}' +
    '.footer-note{text-align:center;font-size:7.5pt;color:#888;margin-top:10px;border-top:1px solid #ddd;padding-top:8px;}';

  const html = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>PIP Document - ${pip.id}</title><style>${style}</style></head>
<body>
<div class="page">
<div class="header"><img src="${UWEZO_LOGO}" class="logo-img" alt="Uwezo Fund" /></div>
<div class="org-name">UWEZO FUND OVERSIGHT BOARD</div>
<div class="org-sub">SECRETARIAT</div>
<div class="org-addr">Lenrho House, 16th Floor, Standard Street, Nairobi &nbsp;|&nbsp; P.O. Box 42009-00100, NAIROBI</div>
<hr class="thick-line">
<div class="doc-title">PERFORMANCE IMPROVEMENT PLAN</div>

<div style="text-align:right;margin-bottom:15px;font-size:9pt;color:#666;">
Date: ${new Date().toLocaleDateString('en-KE')}<br>
Reference: ${pip.id}
</div>

<div class="section">
<div class="section-title">EMPLOYEE INFORMATION</div>
<table class="table">
<tr><td>Employee Name</td><td>${pip.employeeName}</td></tr>
<tr><td>Department</td><td>${pip.dept}</td></tr>
<tr><td>Supervisor</td><td>${pip.hod}</td></tr>
</table>
</div>

<div class="section">
<div class="section-title">PIP DETAILS</div>
<table class="table">
<tr><td>PIP Duration</td><td>${pip.duration}</td></tr>
<tr><td>Start Date</td><td>${pip.startDate}</td></tr>
<tr><td>End Date</td><td>${pip.endDate}</td></tr>
<tr><td>Trigger Rating</td><td>${pip.triggerRating.toFixed(1)}/5</td></tr>
<tr><td>Appraisal Period</td><td>${pip.appraisalPeriod}</td></tr>
<tr><td>Current Progress</td><td>${pip.checkIns[pip.checkIns.length - 1]?.progress || 0}%</td></tr>
</table>
</div>

<div class="section">
<div class="section-title">IMPROVEMENT AREAS</div>
<ol>
${pip.improvementAreas.map(area => `<li>${area}</li>`).join('')}
</ol>
</div>

<div class="section">
<div class="section-title">ACTION PLAN</div>
<p style="font-size:9.5pt;line-height:1.6;white-space:pre-line;">${pip.actionPlan}</p>
</div>

<div class="section">
<div class="section-title">SUCCESS METRICS</div>
<p style="font-size:9.5pt;line-height:1.6;white-space:pre-line;">${pip.successMetrics}</p>
</div>

<div class="section">
<div class="section-title">STATUS</div>
<p><span class="badge">${pip.status.toUpperCase()}</span></p>
<p style="font-size:9.5pt;margin-top:8px;">This PIP has been reviewed and is currently <strong>${pip.status}</strong>.</p>
</div>

<div class="signature-area">
<div class="signature-box">
<div class="signature-line">HR MANAGER<br>Uwezo Fund</div>
</div>
<div class="signature-box">
<div class="signature-line">${pip.hod}<br>Supervisor</div>
</div>
</div>

<div class="footer-bar">
<span>10th Anniversary</span>
<span>AHADI YETU KAZI KWAKO</span>
<span>Kenya Vision 2030</span>
</div>
<div class="footer-note">Uwezo Fund HRMS v2.0.1 &bull; ${new Date().getFullYear()} Uwezo Fund Oversight Board</div>
</div>
</body>
</html>`;

  import('../../../lib/autoDownloadPdf').then(({ printHtmlInIframe }) => {
    printHtmlInIframe(html, 30000).catch(() => {});
  });
}

export default function PIPTab() {
  const [pips, setPips] = useState<PIP[]>(initialPIPs);
  const [expandedId, setExpandedId] = useState<string | null>(pips[0]?.id || null);
  const [showNew, setShowNew] = useState(false);
  const [deptFilter, setDeptFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState('All');
  const [search, setSearch] = useState('');
  const [newForm, setNewForm] = useState({
    employeeId: '',
    duration: '90 days' as '30 days' | '60 days' | '90 days',
    improvementAreas: '',
    actionPlan: '',
    successMetrics: '',
    startDate: '',
  });
  const [addCheckIn, setAddCheckIn] = useState<string | null>(null);
  const [checkInForm, setCheckInForm] = useState({ progress: 50, notes: '' });

  const lowRatingAppraisals = initialAppraisals.filter(a => a.overallRating > 0 && a.overallRating < 2.5);
  const bottom10Pct = initialAppraisals
    .filter(a => a.overallRating > 0)
    .sort((a, b) => a.overallRating - b.overallRating)
    .slice(0, Math.max(1, Math.floor(initialAppraisals.filter(a => a.overallRating > 0).length * 0.1)));

  const pipCandidates = [...new Map([...lowRatingAppraisals, ...bottom10Pct].map(a => [a.employeeId, a])).values()];

  const DEPARTMENTS = ['All', 'Operations', 'ICT', 'Finance', 'M&E', 'HR', 'Communications'];

  const filtered = pips.filter(p =>
    (deptFilter === 'All' || p.dept === deptFilter) &&
    (statusFilter === 'All' || p.status === statusFilter) &&
    (p.employeeName.toLowerCase().includes(search.toLowerCase()) || p.dept.toLowerCase().includes(search.toLowerCase()))
  );

  const handleGenerateAIPIP = () => {
    if (!newForm.employeeId) return;
    const emp = ALL_EMPLOYEES.find(e => e.id === newForm.employeeId);
    const appraisal = initialAppraisals.find(a => a.employeeId === newForm.employeeId);
    if (!emp || !appraisal) return;
    const rating = appraisal.overallRating;
    const dept = emp.dept;
    const role = emp.position;

    const aiImprovementAreas = [
      `Improve ${role.toLowerCase()} core competencies and technical skills relevant to ${dept} operations`,
      `Enhance productivity and timeliness in delivering assigned tasks and departmental targets`,
      `Strengthen communication and collaboration within the ${dept} team and cross-functional units`,
      `Demonstrate measurable improvement in quality of work outputs and adherence to SOPs`,
      rating < 2.0 ? `Urgently address recurring performance gaps identified during ${appraisal.period} appraisal` : `Build on ${appraisal.period} appraisal feedback to achieve consistent above-average performance`,
    ];

    const aiActionPlan = [
      `Week 1-2: Conduct skills gap assessment with HOD (${emp.hod}) and enroll in targeted training programs`,
      `Week 3-4: Implement daily task planning and weekly progress reporting to direct supervisor`,
      `Week 5-8: Participate in peer mentoring sessions and complete at least 2 knowledge-sharing workshops`,
      `Week 9-10: Undertake a mini-project with clear deliverables to demonstrate applied learning`,
      `Week 11-12: Final evaluation meeting with HOD and HR to review progress against PIP objectives`,
    ].join('\n');

    const aiSuccessMetrics = [
      `Achieve minimum performance rating of 3.0/5.0 in the next quarterly appraisal (up from ${rating.toFixed(1)})`,
      `Submit 100% of assigned tasks on time with zero quality complaints for 60 consecutive days`,
      `Complete at least one relevant professional development course with certificate submission`,
      `Receive positive feedback from at least 2 peers and direct supervisor on teamwork and collaboration`,
      `Demonstrate application of learned skills through documented process improvements or efficiency gains`,
    ].join('\n');

    setNewForm(f => ({
      ...f,
      improvementAreas: aiImprovementAreas.join('\n'),
      actionPlan: aiActionPlan,
      successMetrics: aiSuccessMetrics,
      startDate: f.startDate || new Date().toISOString().split('T')[0],
    }));
  };

  const handleCreatePIP = () => {
    const emp = ALL_EMPLOYEES.find(e => e.id === newForm.employeeId);
    if (!emp || !newForm.startDate) return;
    const daysMap = { '30 days': 30, '60 days': 60, '90 days': 90 };
    const start = new Date(newForm.startDate);
    const end = new Date(start);
    end.setDate(end.getDate() + daysMap[newForm.duration]);
    const appraisal = initialAppraisals.find(a => a.employeeId === newForm.employeeId);
    const newPIP: PIP = {
      id: `PIP-2026-${String(pips.length + 1).padStart(3, '0')}`,
      employeeId: newForm.employeeId,
      employeeName: emp.name,
      dept: emp.dept,
      hod: emp.hod,
      triggerRating: appraisal?.overallRating || 0,
      appraisalPeriod: 'Q1 2026',
      startDate: newForm.startDate,
      endDate: end.toISOString().split('T')[0],
      duration: newForm.duration,
      improvementAreas: newForm.improvementAreas.split('\n').filter(Boolean),
      actionPlan: newForm.actionPlan,
      successMetrics: newForm.successMetrics,
      status: 'Active',
      checkIns: [],
    };
    setPips(prev => [newPIP, ...prev]);
    setShowNew(false);
    setNewForm({ employeeId: '', duration: '90 days', improvementAreas: '', actionPlan: '', successMetrics: '', startDate: '' });
  };

  const handleAddCheckIn = (pipId: string) => {
    setPips(prev => prev.map(p => p.id === pipId ? {
      ...p,
      checkIns: [...p.checkIns, {
        date: new Date().toISOString().split('T')[0],
        author: p.hod,
        progress: checkInForm.progress,
        notes: checkInForm.notes,
      }],
    } : p));
    setAddCheckIn(null);
    setCheckInForm({ progress: 50, notes: '' });
  };

  const handleMarkSuccessful = (pipId: string) => {
    setPips(prev => prev.map(p => p.id === pipId ? { ...p, status: 'Successful' } : p));
    const pip = pips.find(p => p.id === pipId);
    if (pip) downloadPIPPdf(pip);
  };

  return (
    <div>
      <div className="grid grid-cols-4 gap-4 mb-5">
        {[
          { label: 'Total PIPs', value: pips.length, icon: 'ri-alarm-warning-line', color: 'bg-yellow-50 text-yellow-600' },
          { label: 'Active', value: pips.filter(p => p.status === 'Active').length, icon: 'ri-time-line', color: 'bg-orange-50 text-orange-600' },
          { label: 'Successful', value: pips.filter(p => p.status === 'Successful').length, icon: 'ri-checkbox-circle-line', color: 'bg-green-50 text-green-600' },
          { label: 'PIP Candidates', value: pipCandidates.length, icon: 'ri-alert-line', color: 'bg-red-50 text-red-600' },
        ].map((s, i) => (
          <motion.div
            key={s.label}
            initial={{ opacity: 0, y: 12, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            transition={{ duration: 0.4, delay: i * 0.1 }}
            whileHover={{ scale: 1.02, y: -4, boxShadow: '0 12px 40px rgba(178, 38, 152, 0.08)' }}
            className="bg-white border border-gray-100 rounded-xl p-4 flex items-center gap-3 shadow-sm cursor-pointer"
          >
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${s.color}`}>
              <i className={`${s.icon} text-lg`}></i>
            </div>
            <div>
              <div className="text-xl font-bold text-gray-800">{s.value}</div>
              <div className="text-xs text-gray-500">{s.label}</div>
            </div>
          </motion.div>
        ))}
      </div>

      {pipCandidates.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
          className="bg-red-50 border border-red-200 rounded-xl p-4 mb-5"
        >
          <div className="flex items-center gap-2 mb-3">
            <div className="w-5 h-5 flex items-center justify-center"><i className="ri-alarm-warning-line text-red-600 text-sm"></i></div>
            <p className="text-sm font-semibold text-red-800">Employees Flagged for PIP (Rating below 2.5/5 or bottom 10%)</p>
          </div>
          <div className="flex flex-wrap gap-2">
            {pipCandidates.map(a => (
              <div key={a.id} className="flex items-center gap-2 bg-white border border-red-200 rounded-lg px-3 py-2">
                <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: '#b828a0' }}>{a.avatar}</div>
                <div>
                  <p className="text-xs font-semibold text-gray-800">{a.name}</p>
                  <p className="text-xs text-red-600 font-medium">{a.overallRating.toFixed(1)}/5 — {RATING_LABELS[Math.round(a.overallRating)] || 'Needs Improvement'}</p>
                </div>
                {!pips.find(p => p.employeeId === a.employeeId && p.status === 'Active') && (
                  <button
                    onClick={() => { setNewForm(f => ({ ...f, employeeId: a.employeeId })); setShowNew(true); }}
                    className="text-xs px-2 py-1 rounded-lg text-white cursor-pointer whitespace-nowrap"
                    style={{ background: '#b828a0' }}
                  >
                    Initiate PIP
                  </button>
                )}
                {pips.find(p => p.employeeId === a.employeeId && p.status === 'Active') && (
                  <span className="text-xs px-2 py-1 rounded-lg bg-yellow-100 text-yellow-700 font-medium">PIP Active</span>
                )}
              </div>
            ))}
          </div>
        </motion.div>
      )}

      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3 flex-wrap">
          <div className="relative">
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search employee..." className="bg-white border border-gray-200 rounded-lg px-4 py-2 text-sm w-44 outline-none pr-8" />
            <div className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2"><i className="ri-search-line text-gray-400 text-sm"></i></div>
          </div>
          <select value={deptFilter} onChange={e => setDeptFilter(e.target.value)} className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none bg-white pr-8 cursor-pointer">
            {DEPARTMENTS.map(d => <option key={d}>{d === 'All' ? 'All Departments' : d}</option>)}
          </select>
          <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none bg-white pr-8 cursor-pointer">
            {['All', 'Active', 'Successful', 'Extended', 'Terminated'].map(s => <option key={s}>{s === 'All' ? 'All Statuses' : s}</option>)}
          </select>
        </div>
        <button
          onClick={() => { setShowNew(true); setNewForm({ employeeId: '', duration: '90 days', improvementAreas: '', actionPlan: '', successMetrics: '', startDate: '' }); }}
          className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap"
          style={{ background: '#b828a0' }}
        >
          <div className="w-4 h-4 flex items-center justify-center"><i className="ri-add-line text-sm"></i></div>
          Initiate PIP
        </button>
      </div>

      {showNew && (
        <div className="bg-white border border-gray-200 rounded-2xl p-5 shadow-sm mb-5">
          <div className="flex items-center justify-between mb-3">
            <h3 className="font-semibold text-gray-800">Initiate New PIP</h3>
            <button onClick={() => setShowNew(false)} className="w-7 h-7 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer"><i className="ri-close-line text-gray-500"></i></button>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">Employee</label>
              <select value={newForm.employeeId} onChange={e => setNewForm(f => ({ ...f, employeeId: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select employee...</option>
                {ALL_EMPLOYEES.map(e => <option key={e.id} value={e.id}>{e.name} — {e.dept}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">PIP Duration</label>
              <select value={newForm.duration} onChange={e => setNewForm(f => ({ ...f, duration: e.target.value as any }))} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer">
                <option>30 days</option><option>60 days</option><option>90 days</option>
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">Start Date</label>
              <input type="date" value={newForm.startDate} onChange={e => setNewForm(f => ({ ...f, startDate: 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-medium text-gray-600 mb-1">Improvement Areas (one per line)</label>
              <textarea value={newForm.improvementAreas} onChange={e => setNewForm(f => ({ ...f, improvementAreas: e.target.value }))} rows={3} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="List specific areas needing improvement..." />
            </div>
            <div className="col-span-2">
              <label className="block text-xs font-medium text-gray-600 mb-1">Action Plan</label>
              <textarea value={newForm.actionPlan} onChange={e => setNewForm(f => ({ ...f, actionPlan: e.target.value }))} rows={3} maxLength={500} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none resize-none" placeholder="Specific steps and timeline..." />
            </div>
            <div className="col-span-2">
              <label className="block text-xs font-medium text-gray-600 mb-1">Success Metrics</label>
              <textarea value={newForm.successMetrics} onChange={e => setNewForm(f => ({ ...f, successMetrics: 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="Measurable criteria for successful completion..." />
            </div>
          </div>
          <div className="flex gap-2 mt-4 flex-wrap">
            <button onClick={() => setShowNew(false)} className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
            {newForm.employeeId && (
              <button onClick={handleGenerateAIPIP}
                className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap flex items-center gap-1.5"
                style={{ background: '#6366f1' }}>
                <i className="ri-magic-line"></i> AI Suggest PIP
              </button>
            )}
            <button onClick={handleCreatePIP} className="px-4 py-2 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Create PIP</button>
          </div>
        </div>
      )}

      <div className="space-y-4">
        {filtered.map((pip, i) => (
          <motion.div
            key={pip.id}
            initial={{ opacity: 0, y: 16 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.35, delay: i * 0.08 }}
            whileHover={{ scale: 1.01, y: -2, boxShadow: '0 8px 24px rgba(0,0,0,0.06)' }}
            className="bg-white border border-gray-100 rounded-2xl shadow-sm overflow-hidden cursor-pointer"
          >
            <div className="p-5 cursor-pointer" onClick={() => setExpandedId(expandedId === pip.id ? null : pip.id)}>
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm" style={{ background: '#b828a0' }}>
                    {pip.employeeName.split(' ').map(n => n[0]).join('').slice(0, 2)}
                  </div>
                  <div>
                    <p className="font-semibold text-gray-800">{pip.employeeName}</p>
                    <p className="text-xs text-gray-500">{pip.dept} · HOD: {pip.hod}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[pip.status]}`}>{pip.status}</span>
                  <span className="text-xs text-gray-400">{pip.duration}</span>
                  <div className="w-4 h-4 flex items-center justify-center"><i className={`${expandedId === pip.id ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'} text-gray-400`}></i></div>
                </div>
              </div>
              <div className="flex items-center gap-3 mb-1">
                <div className="flex-1 bg-gray-100 rounded-full h-2.5">
                  <div className="h-2.5 rounded-full transition-all" style={{ width: `${pip.checkIns[pip.checkIns.length - 1]?.progress || 0}%`, background: '#b828a0' }}></div>
                </div>
                <span className="text-sm font-bold text-gray-700">{pip.checkIns[pip.checkIns.length - 1]?.progress || 0}%</span>
              </div>
              <div className="flex items-center gap-4 text-xs text-gray-400">
                <span>Trigger Rating: <span className="text-red-600 font-semibold">{pip.triggerRating.toFixed(1)}/5 — {RATING_LABELS[Math.round(pip.triggerRating)] || 'Needs Improvement'}</span></span>
                <span>{pip.startDate} → {pip.endDate}</span>
                <span>{pip.id}</span>
              </div>
            </div>

            {expandedId === pip.id && (
              <div className="border-t border-gray-100 px-5 pb-5">
                <div className="grid grid-cols-2 gap-5 pt-4">
                  <div>
                    <p className="text-xs font-semibold text-gray-600 mb-2">Improvement Areas</p>
                    <ul className="space-y-1">
                      {pip.improvementAreas.map((area, i) => (
                        <li key={i} className="flex items-start gap-2 text-sm text-gray-600">
                          <div className="w-4 h-4 flex items-center justify-center mt-0.5 flex-shrink-0"><i className="ri-arrow-right-s-line text-sm" style={{ color: '#b828a0' }}></i></div>
                          {area}
                        </li>
                      ))}
                    </ul>
                  </div>
                  <div>
                    <p className="text-xs font-semibold text-gray-600 mb-2">Success Metrics</p>
                    <p className="text-sm text-gray-600 bg-green-50 border border-green-100 rounded-lg p-3">{pip.successMetrics}</p>
                  </div>
                  <div className="col-span-2">
                    <p className="text-xs font-semibold text-gray-600 mb-2">Action Plan</p>
                    <p className="text-sm text-gray-600 bg-gray-50 rounded-lg p-3 whitespace-pre-line">{pip.actionPlan}</p>
                  </div>
                  <div className="col-span-2">
                    <p className="text-xs font-semibold text-gray-600 mb-2">Check-in History ({pip.checkIns.length})</p>
                    <div className="space-y-2">
                      {pip.checkIns.map((ci, i) => (
                        <div key={i} className="bg-gray-50 rounded-xl p-3 flex items-start gap-3">
                          <div className="text-center flex-shrink-0">
                            <div className="text-lg font-bold" style={{ color: '#b828a0' }}>{ci.progress}%</div>
                            <div className="text-xs text-gray-400">{ci.date}</div>
                          </div>
                          <div>
                            <p className="text-xs font-medium text-gray-700 mb-0.5">{ci.author}</p>
                            <p className="text-xs text-gray-600">{ci.notes}</p>
                          </div>
                        </div>
                      ))}
                      {pip.checkIns.length === 0 && <p className="text-xs text-gray-400">No check-ins recorded yet</p>}
                    </div>
                  </div>
                </div>

                {addCheckIn === pip.id && (
                  <div className="mt-3 bg-gray-50 border border-gray-200 rounded-xl p-4">
                    <p className="text-sm font-semibold text-gray-700 mb-3">Add Check-in</p>
                    <div className="space-y-3">
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Progress: {checkInForm.progress}%</label>
                        <input type="range" min={0} max={100} value={checkInForm.progress} onChange={e => setCheckInForm(f => ({ ...f, progress: +e.target.value }))} className="w-full cursor-pointer" style={{ accentColor: '#b828a0' }} />
                      </div>
                      <div>
                        <label className="text-xs font-medium text-gray-600 block mb-1">Notes</label>
                        <textarea value={checkInForm.notes} onChange={e => setCheckInForm(f => ({ ...f, notes: 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" />
                      </div>
                      <div className="flex gap-2">
                        <button onClick={() => setAddCheckIn(null)} className="px-3 py-1.5 border border-gray-200 rounded-lg text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
                        <button onClick={() => handleAddCheckIn(pip.id)} className="px-3 py-1.5 rounded-lg text-sm font-medium text-white cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Save Check-in</button>
                      </div>
                    </div>
                  </div>
                )}

                <div className="flex gap-2 mt-4 flex-wrap">
                  <button onClick={() => setAddCheckIn(pip.id)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
                    <div className="w-4 h-4 flex items-center justify-center"><i className="ri-add-line text-sm"></i></div>
                    Add Check-in
                  </button>
                  {pip.status === 'Active' && (
                    <button onClick={() => handleMarkSuccessful(pip.id)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium text-green-700 bg-green-50 border border-green-200 cursor-pointer whitespace-nowrap">
                      <div className="w-4 h-4 flex items-center justify-center"><i className="ri-checkbox-circle-line text-sm"></i></div>
                      Mark Successful
                    </button>
                  )}
                  <button onClick={() => downloadPIPPdf(pip)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
                    <div className="w-4 h-4 flex items-center justify-center"><i className="ri-file-download-line text-sm"></i></div>
                    Download PIP Document
                  </button>
                </div>
              </div>
            )}
          </motion.div>
        ))}
        {filtered.length === 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="text-center py-12 text-gray-400 text-sm bg-white rounded-xl border border-gray-100"
          >No PIPs found</motion.div>
        )}
      </div>
    </div>
  );
}