import React, { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  ArrowLeft, EnvelopeSimple, Phone, MapPin, CalendarBlank, Briefcase,
  CurrencyDollar, Buildings, IdentificationBadge, Star, TrendUp,
  UserCircle, ClockCounterClockwise, ShieldCheck, Warning, Plus, X,
  CalendarCheck, FirstAid, Clock, Prohibit, Pencil, Trophy, FileText,
  ArrowUp, ArrowDown, UserMinus, Note, HandCoins
} from '@phosphor-icons/react';
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid, ResponsiveContainer, Cell
} from 'recharts';
import axios from 'axios';
import toast from 'react-hot-toast';

const BRAND = '#5D4037';

const SC = {
  'active':     { label:'Active',     bg:'#dcfce7', text:'#15803d' },
  'on-leave':   { label:'On Leave',   bg:'#fef9c3', text:'#a16207' },
  'terminated': { label:'Terminated', bg:'#fee2e2', text:'#dc2626' },
  'resigned':   { label:'Resigned',   bg:'#f3f4f6', text:'#4b5563' },
};
const EVT = {
  award:            { icon: Trophy,    bg:'#fef9c3', text:'#a16207', label:'Award' },
  review:           { icon: Star,      bg:'#e0e7ff', text:'#4338ca', label:'Review' },
  fine:             { icon: ArrowDown, bg:'#fee2e2', text:'#dc2626', label:'Fine' },
  department_change:{ icon: Buildings, bg:'#EFEBE9', text:'#4E342E', label:'Dept Change' },
  status_change:    { icon: Prohibit,  bg:'#f0fdf4', text:'#166534', label:'Status' },
  note:             { icon: Note,      bg:'#f9fafb', text:'#374151', label:'Note' },
  termination:      { icon: UserMinus, bg:'#fee2e2', text:'#dc2626', label:'Termination' },
};
const fmt = v => `₦${Number(v||0).toLocaleString()}`;
const fmtD = d => d ? new Date(d).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'}) : '—';
const Card = ({children,className=''}) => (
  <div className={`bg-white rounded-2xl shadow-sm border border-gray-100 ${className}`}>{children}</div>
);

const TABS = [
  { id:'overview',  label:'Overview',        icon: UserCircle },
  { id:'leave',     label:'Leave',           icon: CalendarCheck },
  { id:'salary',    label:'Salary & Comp.',  icon: CurrencyDollar },
  { id:'events',    label:'Awards & Events', icon: Trophy },
  { id:'loans',     label:'Staff Loans',     icon: HandCoins },
];

// ── Form helpers defined OUTSIDE the component so they never remount on re-render ──
const Inp = ({label, ...p}) => (
  <div>
    <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
    <input className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none" {...p}/>
  </div>
);
const Sel = ({label, children, ...p}) => (
  <div>
    <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
    <select className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white" {...p}>{children}</select>
  </div>
);
const Txt = ({label, ...p}) => (
  <div>
    <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
    <textarea rows={3} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none" {...p}/>
  </div>
);

export default function EmployeeDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [tab, setTab] = useState('overview');
  const [employee, setEmployee]   = useState(null);
  const [loading, setLoading]     = useState(true);
  const [leaves, setLeaves]       = useState([]);
  const [salaryHist, setSalaryH]  = useState([]);
  const [events, setEvents]       = useState([]);
  const [departments, setDepts]   = useState([]);
  const [modal, setModal]         = useState(null); // 'leave'|'salary'|'event'|'status'|'edit'
  const [saving, setSaving]       = useState(false);

  // Staff loans
  const [empLoans, setEmpLoans]           = useState([]);
  const [loansLoading, setLoansLoading]   = useState(false);
  const [loanDeds, setLoanDeds]           = useState({});
  const [openLoanId, setOpenLoanId]       = useState(null);
  const [dedsLoading, setDedsLoading]     = useState(false);
  const [showDeductModal, setShowDeductModal] = useState(false);
  const [selectedDeduction, setSelectedDeduction] = useState(null);
  const [selectedLoanForDeduction, setSelectedLoanForDeduction] = useState(null);
  const [deductForm, setDeductForm] = useState({ payment_method: 'cash', bank_account_id: null });
  const [companyBanks, setCompanyBanks] = useState([]);

  // Forms
  const [leaveForm,  setLF] = useState({ type:'annual', start_date:'', end_date:'', reason:'', status:'approved' });
  const [salaryForm, setSF] = useState({ type:'raise', new_salary:'', amount_change:'', effective_date:'', reason:'' });
  const [eventForm,  setEF] = useState({ type:'award', title:'', description:'', amount:'', event_date: new Date().toISOString().split('T')[0], new_value:'' });
  const [editForm,   setEdit] = useState({});

  const load = useCallback(async () => {
    try {
      const [empR, deptR] = await Promise.all([
        axios.get(`/api/employees/${id}`),
        axios.get('/api/departments'),
      ]);
      setEmployee(empR.data);
      setDepts(deptR.data.data || []);
    } catch { toast.error('Failed to load employee'); navigate('/employees'); }
    finally { setLoading(false); }
  }, [id]);

  const loadLeaves  = async () => { try { const r = await axios.get(`/api/employees/${id}/leaves`); setLeaves(r.data.data || []); } catch {} };
  const loadSalary  = async () => { try { const r = await axios.get(`/api/employees/${id}/salary-history`); setSalaryH(r.data.data || []); } catch {} };
  const loadEvents  = async () => { try { const r = await axios.get(`/api/employees/${id}/events`); setEvents(r.data.data || []); } catch {} };

  const loadEmpLoans = async () => {
    setLoansLoading(true);
    try { const r = await axios.get('/api/staff-loans', { params: { employee_id: id } }); setEmpLoans(r.data.data || []); }
    catch {} finally { setLoansLoading(false); }
  };

  const toggleLoanDeds = async (loanId) => {
    if (openLoanId === loanId) { setOpenLoanId(null); return; }
    setOpenLoanId(loanId); setDedsLoading(true);
    try {
      const r = await axios.get(`/api/staff-loans/${loanId}/deductions`);
      setLoanDeds(p => ({ ...p, [loanId]: r.data.data || [] }));
    } catch { setLoanDeds(p => ({ ...p, [loanId]: [] })); }
    finally { setDedsLoading(false); }
  };

  useEffect(() => { load(); }, [load]);
  useEffect(() => {
    if (tab === 'leave')  loadLeaves();
    if (tab === 'salary') loadSalary();
    if (tab === 'events') loadEvents();
    if (tab === 'loans')  loadEmpLoans();
  }, [tab]);

  const submitLeave = async (e) => {
    e.preventDefault(); setSaving(true);
    try { await axios.post(`/api/employees/${id}/leaves`, leaveForm); toast.success('Leave recorded'); setModal(null); loadLeaves(); load(); }
    catch(err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const submitSalary = async (e) => {
    e.preventDefault(); setSaving(true);
    try { await axios.post(`/api/employees/${id}/salary-change`, salaryForm); toast.success('Salary updated'); setModal(null); setSalaryH([]); load(); loadSalary(); }
    catch(err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const submitEvent = async (e) => {
    e.preventDefault(); setSaving(true);
    try { await axios.post(`/api/employees/${id}/events`, eventForm); toast.success('Event recorded'); setModal(null); loadEvents(); load(); }
    catch(err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const submitEdit = async (e) => {
    e.preventDefault(); setSaving(true);
    try { await axios.put(`/api/employees/${id}`, editForm); toast.success('Employee updated'); setModal(null); load(); }
    catch(err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary-50 to-indigo-50">
      <div className="text-center">
        <div className="w-14 h-14 rounded-full border-4 border-t-transparent mx-auto animate-spin" style={{ borderColor:`${BRAND}33`, borderTopColor:BRAND }} />
        <p className="mt-3 text-sm text-gray-500">Loading employee…</p>
      </div>
    </div>
  );

  const e = employee || {};
  const sc = SC[e.status] || SC['resigned'];
  const tenure = e.hire_date ? Math.floor((new Date() - new Date(e.hire_date)) / (1000*60*60*24*365)) : 0;
  const initials = `${e.first_name?.[0]||''}${e.last_name?.[0]||''}`;

  // Inp, Sel, Txt are defined at module scope above — see top of file

  return (
    <div className="min-h-screen p-4 md:p-6" style={{ background:'linear-gradient(135deg,#EFEBE9 0%,#e8e8fd 50%,#f8faff 100%)' }}>

      {/* Back */}
      <button onClick={() => navigate('/employees')}
        className="flex items-center gap-2 text-sm font-medium mb-5 px-4 py-2 rounded-xl bg-white text-gray-600 hover:text-gray-900 shadow-sm transition-all">
        <ArrowLeft size={16} weight="bold" /> Back to Employees
      </button>

      {/* â”€â”€ Hero â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ */}
      <Card className="p-5 mb-5 flex flex-wrap items-center gap-4">
        <div className="w-16 h-16 rounded-2xl flex items-center justify-center text-white text-xl font-black flex-shrink-0"
             style={{background:`linear-gradient(135deg,${BRAND},#6D4C41)`}}>
          {initials}
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex flex-wrap items-center gap-2 mb-1">
            <h1 className="text-xl font-black text-gray-900">{e.first_name} {e.last_name}</h1>
            <span className="px-2 py-0.5 rounded-full text-xs font-bold" style={{background:sc.bg,color:sc.text}}>{sc.label}</span>
          </div>
          <p className="text-gray-500 text-sm">{e.position} · {e.department?.name} · {e.company?.name}</p>
          <p className="text-xs text-gray-400 mt-0.5">{e.employee_id} · {tenure} yr{tenure!==1?'s':''} tenure · Hired {fmtD(e.hire_date)}</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={()=>{setEdit({first_name:e.first_name,last_name:e.last_name,email:e.email,phone:e.phone,position:e.position,department_id:e.department_id,salary:e.salary,employment_type:e.employment_type,status:e.status,hire_date:e.hire_date,address:e.address,city:e.city,state:e.state,country:e.country,emergency_contact_name:e.emergency_contact_name,emergency_contact_phone:e.emergency_contact_phone});setModal('edit');}}
            className="flex items-center gap-1 px-3 py-2 text-sm font-semibold text-primary-600 bg-primary-50 hover:bg-primary-100 rounded-xl">
            <Pencil size={14}/> Edit
          </button>
          <div className="text-right">
            <p className="text-xl font-black" style={{color:BRAND}}>{fmt(e.salary)}</p>
            <p className="text-xs text-gray-400">Annual Salary</p>
          </div>
        </div>
      </Card>

      {/* â”€â”€ KPI bar â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
        {[
          {label:'Employment Type', value:(e.employment_type||'N/A').replace(/_/g,' ').replace(/-/g,' '), icon:Briefcase, color:'#10b981'},
          {label:'Department',      value:e.department?.name||'â€”',                                         icon:Buildings, color:BRAND},
          {label:'Hire Date',       value:fmtD(e.hire_date),                                               icon:CalendarBlank, color:'#f59e0b'},
          {label:'Status',          value:sc.label,                                                        icon:ShieldCheck, color:sc.text},
        ].map((k,i)=>(
          <Card key={i} className="p-3 flex items-center gap-3">
            <div className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0" style={{background:k.color+'18'}}>
              <k.icon size={16} weight="duotone" style={{color:k.color}}/>
            </div>
            <div><p className="text-sm font-bold text-gray-900 capitalize">{k.value}</p><p className="text-xs text-gray-400">{k.label}</p></div>
          </Card>
        ))}
      </div>

      {/* â”€â”€ Tabs â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€ */}
      <div className="flex gap-1 mb-5 bg-white rounded-2xl p-1 shadow-sm border border-gray-100 overflow-x-auto">
        {TABS.map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)}
            className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold whitespace-nowrap transition-all ${tab===t.id?'text-white shadow':'text-gray-500 hover:text-gray-700'}`}
            style={tab===t.id?{background:BRAND}:{}}>
            <t.icon size={15}/> {t.label}
          </button>
        ))}
      </div>

      {/* â•â•â•â•â•â•â•â•â•â•â• OVERVIEW TAB â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• */}
      {tab==='overview'&&(
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
          <Card className="p-5">
            <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2"><EnvelopeSimple size={16} style={{color:BRAND}}/> Contact</h3>
            <div className="space-y-3">
              {[{icon:EnvelopeSimple,label:'Email',v:e.email},{icon:Phone,label:'Phone',v:e.phone},{icon:MapPin,label:'Address',v:[e.address,e.city,e.state,e.country].filter(Boolean).join(', ')||null}].filter(r=>r.v).map((row,i)=>(
                <div key={i} className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0" style={{background:BRAND+'12'}}>
                    <row.icon size={14} weight="duotone" style={{color:BRAND}}/>
                  </div>
                  <div><p className="text-xs text-gray-400">{row.label}</p><p className="text-sm font-semibold text-gray-800">{row.v}</p></div>
                </div>
              ))}
              {e.emergency_contact_name&&(
                <div className="mt-3 pt-3 border-t border-gray-100">
                  <p className="text-xs text-red-500 font-semibold mb-1 flex items-center gap-1"><Warning size={11}/> Emergency Contact</p>
                  <p className="text-sm font-bold text-gray-800">{e.emergency_contact_name}</p>
                  {e.emergency_contact_phone&&<p className="text-xs text-gray-500">{e.emergency_contact_phone}</p>}
                </div>
              )}
            </div>
          </Card>

          <Card className="p-5">
            <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2"><Briefcase size={16} style={{color:'#10b981'}}/> Employment Details</h3>
            <div className="grid grid-cols-2 gap-3">
              {[
                {label:'Department', v:e.department?.name||'â€”'},
                {label:'Position',   v:e.position||'â€”'},
                {label:'Type',       v:(e.employment_type||'â€”').replace(/_/g,' ').replace(/-/g,' ')},
                {label:'Status',     v:sc.label, color:sc.text},
                {label:'Hire Date',  v:fmtD(e.hire_date)},
                {label:'Termination',v:e.termination_date?fmtD(e.termination_date):'N/A'},
                {label:'Salary',     v:fmt(e.salary)},
                {label:'Company',    v:e.company?.name||'â€”'},
                {label:'Active Loans', v:(()=>{const a=empLoans.filter(l=>['approved','active'].includes(l.status)); return a.length?`${a.length} (${fmt(a.reduce((s,l)=>s+(+l.outstanding_balance||0),0))} owed)` : 'None';})(), color:'#C6A862'},
              ].map((item,i)=>(
                <div key={i} className="bg-gray-50 rounded-xl p-3">
                  <p className="text-xs text-gray-400 mb-0.5">{item.label}</p>
                  <p className="text-sm font-bold capitalize" style={{color:item.color||'#111827'}}>{item.v}</p>
                </div>
              ))}
            </div>
          </Card>
        </div>
      )}

      {/* â•â•â•â•â•â•â•â•â•â•â• LEAVE TAB â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• */}
      {tab==='leave'&&(
        <div>
          <div className="flex justify-end mb-4">
            <button onClick={()=>setModal('leave')} className="flex items-center gap-2 px-4 py-2 text-white text-sm font-semibold rounded-xl shadow" style={{background:BRAND}}>
              <Plus size={15}/> Record Leave
            </button>
          </div>
          <Card className="overflow-hidden">
            <div className="p-4 border-b border-gray-100 font-semibold text-gray-800">Leave History</div>
            {leaves.length===0?(
              <div className="py-14 text-center text-gray-400">
                <CalendarCheck size={40} className="mx-auto mb-2 opacity-30"/>
                <p>No leave records yet</p>
              </div>
            ):(
              <table className="w-full text-sm">
                <thead className="bg-gray-50"><tr>
                  {['Type','Start','End','Days','Reason','Status'].map(h=><th key={h} className="px-4 py-3 text-left text-xs font-semibold text-gray-500">{h}</th>)}
                </tr></thead>
                <tbody className="divide-y divide-gray-50">
                  {leaves.map((l,i)=>(
                    <tr key={i} className="hover:bg-gray-50">
                      <td className="px-4 py-3 capitalize font-medium text-gray-800">{l.type}</td>
                      <td className="px-4 py-3 text-gray-500">{fmtD(l.start_date)}</td>
                      <td className="px-4 py-3 text-gray-500">{fmtD(l.end_date)}</td>
                      <td className="px-4 py-3 font-bold text-gray-800">{l.days}</td>
                      <td className="px-4 py-3 text-gray-500 max-w-xs truncate">{l.reason||'â€”'}</td>
                      <td className="px-4 py-3">
                        <span className={`px-2 py-1 rounded-full text-xs font-bold ${l.status==='approved'?'bg-green-100 text-green-700':l.status==='rejected'?'bg-red-100 text-red-700':'bg-yellow-100 text-yellow-700'}`}>{l.status}</span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </Card>
        </div>
      )}

      {/* â•â•â•â•â•â•â•â•â•â•â• SALARY TAB â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• */}
      {tab==='salary'&&(
        <div>
          <div className="flex justify-between items-center mb-4">
            <div className="bg-white rounded-2xl px-5 py-3 shadow-sm border border-gray-100">
              <p className="text-xs text-gray-400">Current Salary</p>
              <p className="text-2xl font-black" style={{color:BRAND}}>{fmt(e.salary)}</p>
            </div>
            <div className="flex gap-2">
              <button onClick={()=>{setSF({type:'raise',new_salary:'',amount_change:'',effective_date:new Date().toISOString().split('T')[0],reason:''});setModal('salary');}}
                className="flex items-center gap-1 px-4 py-2 text-sm font-semibold text-white rounded-xl shadow" style={{background:'#10b981'}}>
                <ArrowUp size={14}/> Raise
              </button>
              <button onClick={()=>{setSF({type:'fine',new_salary:'',amount_change:'',effective_date:new Date().toISOString().split('T')[0],reason:''});setModal('salary');}}
                className="flex items-center gap-1 px-4 py-2 text-sm font-semibold text-white rounded-xl shadow" style={{background:'#ef4444'}}>
                <ArrowDown size={14}/> Fine / Deduction
              </button>
            </div>
          </div>

          {salaryHist.length>0&&(
            <Card className="p-5 mb-5">
              <h3 className="font-bold text-gray-800 mb-4">Salary Chart</h3>
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={[...salaryHist].reverse().map(h=>({label:fmtD(h.effective_date),salary:+h.new_salary}))}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#EFEBE9"/>
                  <XAxis dataKey="label" tick={{fontSize:10,fill:'#9ca3af'}} axisLine={false} tickLine={false}/>
                  <YAxis tickFormatter={v=>`â‚¦${(v/1000).toFixed(0)}K`} tick={{fontSize:10,fill:'#9ca3af'}} axisLine={false} tickLine={false}/>
                  <Tooltip formatter={v=>[fmt(v),'Salary']}/>
                  <Bar dataKey="salary" radius={[6,6,0,0]}>
                    {salaryHist.map((_,i)=><Cell key={i} fill={i===0?BRAND:BRAND+'88'}/>)}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </Card>
          )}

          <Card className="overflow-hidden">
            <div className="p-4 border-b border-gray-100 font-semibold text-gray-800">Salary Change History</div>
            {salaryHist.length===0?(
              <div className="py-14 text-center text-gray-400"><CurrencyDollar size={40} className="mx-auto mb-2 opacity-30"/><p>No salary changes recorded</p></div>
            ):(
              <table className="w-full text-sm">
                <thead className="bg-gray-50"><tr>
                  {['Date','Type','Previous','New Salary','Change','Reason'].map(h=><th key={h} className="px-4 py-3 text-left text-xs font-semibold text-gray-500">{h}</th>)}
                </tr></thead>
                <tbody className="divide-y divide-gray-50">
                  {salaryHist.map((h,i)=>{
                    const up=h.amount_change>=0;
                    return(
                      <tr key={i} className="hover:bg-gray-50">
                        <td className="px-4 py-3 text-gray-500">{fmtD(h.effective_date)}</td>
                        <td className="px-4 py-3 capitalize font-medium">{h.type}</td>
                        <td className="px-4 py-3 text-gray-500">{fmt(h.old_salary)}</td>
                        <td className="px-4 py-3 font-bold text-gray-900">{fmt(h.new_salary)}</td>
                        <td className="px-4 py-3">
                          <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${up?'bg-green-100 text-green-700':'bg-red-100 text-red-700'}`}>
                            {up?'+':''}{fmt(h.amount_change)}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-gray-500">{h.reason||'â€”'}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </Card>
        </div>
      )}

      {/* â•â•â•â•â•â•â•â•â•â•â• EVENTS TAB â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• */}
      {tab==='events'&&(
        <div>
          <div className="flex flex-wrap justify-end gap-2 mb-4">
            {[{type:'award',label:'Award',color:'#f59e0b'},{type:'review',label:'Review',color:BRAND},{type:'fine',label:'Fine',color:'#ef4444'},{type:'department_change',label:'Dept Change',color:'#10b981'},{type:'status_change',label:'Status Change',color:'#8b5cf6'},{type:'note',label:'Add Note',color:'#6b7280'},{type:'termination',label:'Termination',color:'#dc2626'}].map(btn=>(
              <button key={btn.type} onClick={()=>{setEF({type:btn.type,title:'',description:'',amount:'',event_date:new Date().toISOString().split('T')[0],new_value:''});setModal('event');}}
                className="px-3 py-1.5 text-xs font-semibold text-white rounded-xl" style={{background:btn.color}}>
                + {btn.label}
              </button>
            ))}
          </div>

          {events.length===0?(
            <Card className="py-14 text-center text-gray-400">
              <Trophy size={40} className="mx-auto mb-2 opacity-30"/><p>No events recorded yet</p>
            </Card>
          ):(
            <div className="space-y-3">
              {events.map((ev,i)=>{
                const cfg=EVT[ev.type]||EVT.note;
                const Ico=cfg.icon;
                return(
                  <Card key={i} className="p-4 flex items-start gap-4">
                    <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{background:cfg.bg}}>
                      <Ico size={18} style={{color:cfg.text}}/>
                    </div>
                    <div className="flex-1">
                      <div className="flex flex-wrap items-center gap-2 mb-1">
                        <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{background:cfg.bg,color:cfg.text}}>{cfg.label}</span>
                        <span className="font-semibold text-gray-900">{ev.title}</span>
                        {ev.amount&&<span className="text-xs font-bold text-red-600">{fmt(ev.amount)}</span>}
                      </div>
                      {ev.description&&<p className="text-sm text-gray-600">{ev.description}</p>}
                      {(ev.old_value||ev.new_value)&&<p className="text-xs text-gray-400 mt-1">{ev.old_value} â†’ {ev.new_value}</p>}
                    </div>
                    <p className="text-xs text-gray-400 whitespace-nowrap">{fmtD(ev.event_date)}</p>
                  </Card>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* â•â•â•â•â•â•â•â•â•â•â• MODALS â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• */}

      {/* Staff Loans Tab */}
      {tab==='loans'&&(
        <div>
          {loansLoading ? (
            <div className="flex justify-center py-12"><div className="w-8 h-8 rounded-full border-4 border-t-transparent border-purple-600 animate-spin"/></div>
          ) : empLoans.length===0 ? (
            <Card className="py-14 text-center text-gray-400">
              <HandCoins size={40} className="mx-auto mb-2 opacity-30"/><p>No staff loans on record</p>
            </Card>
          ) : (
            <div className="space-y-4">
              {empLoans.map(loan=>{
                const isOpen = openLoanId === loan.id;
                const deds = loanDeds[loan.id] || [];
                const totalDed = deds.filter(d=>d.status==='deducted').reduce((s,d)=>s+(+d.deduction_amount||0),0);
                return (
                  <Card key={loan.id} className="p-4">
                    <div className="flex flex-wrap items-center justify-between gap-3 mb-3">
                      <div>
                        <p className="font-bold text-gray-900">{loan.loan_number}</p>
                        <p className="text-xs text-gray-500">{fmt(loan.principal_amount)} principal · {loan.interest_rate||0}% · {loan.term_months} months</p>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className={`px-2 py-0.5 rounded-full text-xs font-bold border capitalize ${
                          loan.status==='paid_off'?'bg-green-100 text-green-700 border-green-200':
                          loan.status==='approved'||loan.status==='active'?'bg-primary-100 text-primary-700 border-primary-200':
                          loan.status==='rejected'?'bg-red-100 text-red-700 border-red-200':
                          'bg-gray-100 text-gray-600 border-gray-200'
                        }`}>{loan.status}</span>
                        <button onClick={()=>toggleLoanDeds(loan.id)} className="text-xs bg-purple-50 text-purple-700 px-2 py-1 rounded-lg font-semibold hover:bg-purple-100">
                          {isOpen?'Hide':'View'} Schedule
                        </button>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-sm mb-2">
                      <div className="bg-gray-50 rounded-lg p-2"><p className="text-xs text-gray-400">Outstanding</p><p className="font-bold">{fmt(loan.outstanding_balance)}</p></div>
                      <div className="bg-gray-50 rounded-lg p-2"><p className="text-xs text-gray-400">Monthly</p><p className="font-bold">{loan.deduction_type==='percentage'?`${loan.deduction_value}%`:fmt(loan.deduction_value)}</p></div>
                      <div className="bg-gray-50 rounded-lg p-2"><p className="text-xs text-gray-400">Purpose</p><p className="font-bold truncate">{loan.purpose||'—'}</p></div>
                      <div className="bg-gray-50 rounded-lg p-2"><p className="text-xs text-gray-400">Paid So Far</p><p className="font-bold">{fmt(totalDed)}</p></div>
                    </div>
                    {isOpen && (
                      <div className="mt-3 border border-gray-100 rounded-xl overflow-x-auto">
                        {dedsLoading && !loanDeds[loan.id] ? (
                          <div className="flex justify-center py-4"><div className="w-5 h-5 rounded-full border-2 border-t-transparent border-purple-600 animate-spin"/></div>
                        ) : (
                          <table className="w-full text-sm">
                            <thead className="bg-gray-50"><tr>
                              {['Month','Due Date','Deduction','Principal','Interest','Status','Action'].map(h=><th key={h} className="px-3 py-2 text-left text-xs font-semibold text-gray-500">{h}</th>)}
                            </tr></thead>
                            <tbody className="divide-y divide-gray-50">
                              {deds.length===0 && <tr><td colSpan={7} className="py-6 text-center text-gray-400 text-xs">No schedule generated yet</td></tr>}
                              {deds.map((d,di)=>{
                                const canMark = d.status==='scheduled' && (loan.status==='approved'||loan.status==='active');
                                return (
                                  <tr key={d.id||di} className="hover:bg-gray-50">
                                    <td className="px-3 py-2 font-medium">{d.month_number}</td>
                                    <td className="px-3 py-2 text-gray-500 text-xs">{fmtD(d.due_date)}</td>
                                    <td className="px-3 py-2 font-bold">{fmt(d.deduction_amount)}</td>
                                    <td className="px-3 py-2 text-gray-500 text-xs">{fmt(d.principal_portion)}</td>
                                    <td className="px-3 py-2 text-gray-500 text-xs">{fmt(d.interest_portion)}</td>
                                    <td className="px-3 py-2">
                                      <span className={`px-2 py-0.5 rounded-full text-xs font-bold border capitalize ${
                                        d.status==='deducted'?'bg-green-100 text-green-700 border-green-200':
                                        d.status==='missed'?'bg-red-100 text-red-700 border-red-200':
                                        'bg-gray-100 text-gray-600 border-gray-200'
                                      }`}>{d.status}</span>
                                    </td>
                                    <td className="px-3 py-2">
                                      {canMark ? (
                                        <button onClick={async()=>{
                                            setSelectedDeduction(d);
                                            setSelectedLoanForDeduction(loan.id);
                                            setDeductForm({ payment_method: 'cash', bank_account_id: null });
                                            // Load company bank accounts for selection
                                            try {
                                              const res = await axios.get(`/api/bank-accounts`, { params: { company_id: e.company?.id || loan.company_id } });
                                              setCompanyBanks(res.data.data || []);
                                            } catch (err) { setCompanyBanks([]); }
                                            setShowDeductModal(true);
                                          }}
                                          className="px-2 py-0.5 text-xs bg-purple-600 text-white rounded-lg font-semibold hover:bg-purple-700">Mark</button>
                                      ) : d.status==='deducted' ? (
                                        <span className="text-xs text-gray-400">{fmtD(d.deducted_on)}</span>
                                      ) : null}
                                    </td>
                                  </tr>
                                );
                              })}
                            </tbody>
                          </table>
                        )}
                      </div>
                    )}
                  </Card>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* Deduction Payment Modal */}
      {showDeductModal && selectedDeduction && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setShowDeductModal(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md" onClick={ev=>ev.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b"><h3 className="font-bold text-gray-900">Mark Deduction Paid</h3><button onClick={()=>setShowDeductModal(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button></div>
            <div className="p-5 space-y-4">
              <p className="text-sm text-gray-600">Amount: <span className="font-bold">{fmt(selectedDeduction.deduction_amount)}</span></p>
              <Sel label="Payment Method" value={deductForm.payment_method} onChange={ev=>setDeductForm(p=>({...p,payment_method:ev.target.value, bank_account_id: null}))}>
                <option value="cash">Cash</option>
                <option value="bank">Bank Transfer</option>
              </Sel>
              {deductForm.payment_method === 'bank' && (
                <Sel label="Bank Account" value={deductForm.bank_account_id || ''} onChange={ev=>setDeductForm(p=>({...p,bank_account_id:ev.target.value||null}))}>
                  <option value="">Select bank account</option>
                  {companyBanks.map(b=> <option key={b.id} value={b.id}>{b.bank_name} - {b.account_number}</option>)}
                </Sel>
              )}
              <div className="flex justify-end gap-2">
                <button type="button" onClick={()=>setShowDeductModal(false)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm">Cancel</button>
                <button type="button" onClick={async()=>{
                    try {
                      const payload = { payment_method: deductForm.payment_method };
                      if (deductForm.payment_method === 'bank') payload.bank_account_id = deductForm.bank_account_id;
                      await axios.post(`/api/staff-loan-deductions/${selectedDeduction.id}/mark-deducted`, payload);
                      toast.success('Deduction recorded');
                      setShowDeductModal(false);
                      // refresh deductions for the loan
                      if (selectedLoanForDeduction) toggleLoanDeds(selectedLoanForDeduction);
                    } catch (er) {
                      toast.error(er.response?.data?.message || 'Failed');
                    }
                  }} className="px-4 py-2 text-white rounded-xl text-sm font-semibold" style={{background:BRAND}}>Mark Paid</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Edit Employee */}
      {modal==='edit'&&(
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setModal(null)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto" onClick={e2=>e2.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b"><h3 className="font-bold text-lg text-gray-900">Edit Employee</h3><button onClick={()=>setModal(null)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button></div>
            <form onSubmit={submitEdit} className="p-5 grid grid-cols-1 md:grid-cols-2 gap-4">
              <Inp label="First Name" value={editForm.first_name||''} onChange={ev=>setEdit(p=>({...p,first_name:ev.target.value}))}/>
              <Inp label="Last Name"  value={editForm.last_name||''} onChange={ev=>setEdit(p=>({...p,last_name:ev.target.value}))}/>
              <Inp label="Email" type="email" value={editForm.email||''} onChange={ev=>setEdit(p=>({...p,email:ev.target.value}))}/>
              <Inp label="Phone" value={editForm.phone||''} onChange={ev=>setEdit(p=>({...p,phone:ev.target.value}))}/>
              <Inp label="Position" value={editForm.position||''} onChange={ev=>setEdit(p=>({...p,position:ev.target.value}))}/>
              <Sel label="Department" value={editForm.department_id||''} onChange={ev=>setEdit(p=>({...p,department_id:ev.target.value}))}>
                <option value="">Select department</option>
                {departments.map(d=><option key={d.id} value={d.id}>{d.name}</option>)}
              </Sel>
              <Inp label="Salary (â‚¦)" type="number" value={editForm.salary||''} onChange={ev=>setEdit(p=>({...p,salary:ev.target.value}))}/>
              <Sel label="Status" value={editForm.status||''} onChange={ev=>setEdit(p=>({...p,status:ev.target.value}))}>
                {['active','on-leave','terminated','resigned'].map(s=><option key={s} value={s}>{s}</option>)}
              </Sel>
              <Sel label="Employment Type" value={editForm.employment_type||''} onChange={ev=>setEdit(p=>({...p,employment_type:ev.target.value}))}>
                <option value="full-time">Full Time</option>
                <option value="part-time">Part Time</option>
                <option value="contract">Contract</option>
                <option value="intern">Intern</option>
              </Sel>
              <Inp label="Hire Date" type="date" value={editForm.hire_date||''} onChange={ev=>setEdit(p=>({...p,hire_date:ev.target.value}))}/>
              <Inp label="City" value={editForm.city||''} onChange={ev=>setEdit(p=>({...p,city:ev.target.value}))}/>
              <Inp label="State" value={editForm.state||''} onChange={ev=>setEdit(p=>({...p,state:ev.target.value}))}/>
              <Inp label="Emergency Contact Name" value={editForm.emergency_contact_name||''} onChange={ev=>setEdit(p=>({...p,emergency_contact_name:ev.target.value}))}/>
              <Inp label="Emergency Contact Phone" value={editForm.emergency_contact_phone||''} onChange={ev=>setEdit(p=>({...p,emergency_contact_phone:ev.target.value}))}/>
              <div className="md:col-span-2 flex justify-end gap-2 pt-2">
                <button type="button" onClick={()=>setModal(null)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2 text-white rounded-xl text-sm font-semibold" style={{background:BRAND}}>{saving?'Saving…':'Save Changes'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Leave Modal */}
      {modal==='leave'&&(
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setModal(null)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md" onClick={ev=>ev.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b"><h3 className="font-bold text-gray-900">Record Leave</h3><button onClick={()=>setModal(null)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button></div>
            <form onSubmit={submitLeave} className="p-5 space-y-4">
              <Sel label="Leave Type" value={leaveForm.type} onChange={ev=>setLF(p=>({...p,type:ev.target.value}))}>
                {['annual','sick','maternity','paternity','unpaid','other'].map(t=><option key={t} value={t}>{t.charAt(0).toUpperCase()+t.slice(1)}</option>)}
              </Sel>
              <div className="grid grid-cols-2 gap-3">
                <Inp label="Start Date" type="date" value={leaveForm.start_date} onChange={ev=>setLF(p=>({...p,start_date:ev.target.value}))} required/>
                <Inp label="End Date"   type="date" value={leaveForm.end_date}   onChange={ev=>setLF(p=>({...p,end_date:ev.target.value}))}   required/>
              </div>
              <Sel label="Status" value={leaveForm.status} onChange={ev=>setLF(p=>({...p,status:ev.target.value}))}>
                <option value="approved">Approved</option>
                <option value="pending">Pending</option>
                <option value="rejected">Rejected</option>
              </Sel>
              <Txt label="Reason" value={leaveForm.reason} onChange={ev=>setLF(p=>({...p,reason:ev.target.value}))}/>
              <div className="flex justify-end gap-2">
                <button type="button" onClick={()=>setModal(null)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2 text-white rounded-xl text-sm font-semibold" style={{background:BRAND}}>{saving?'Saving…':'Record Leave'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Salary Modal */}
      {modal==='salary'&&(
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setModal(null)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md" onClick={ev=>ev.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b"><h3 className="font-bold text-gray-900 capitalize">{salaryForm.type==='fine'?'Fine / Deduction':'Salary Raise / Adjustment'}</h3><button onClick={()=>setModal(null)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button></div>
            <form onSubmit={submitSalary} className="p-5 space-y-4">
              <Sel label="Type" value={salaryForm.type} onChange={ev=>setSF(p=>({...p,type:ev.target.value}))}>
                <option value="raise">Raise</option>
                <option value="bonus">Bonus</option>
                <option value="fine">Fine / Deduction</option>
                <option value="reduction">Salary Reduction</option>
                <option value="adjustment">Salary Adjustment</option>
              </Sel>
              <div className="p-3 bg-gray-50 rounded-xl text-sm"><span className="text-gray-500">Current salary: </span><span className="font-bold">{fmt(e.salary)}</span></div>
              <Inp label="New Salary (₦) — or leave blank to use amount below" type="number" value={salaryForm.new_salary} onChange={ev=>setSF(p=>({...p,new_salary:ev.target.value}))} min="0"/>
              <Inp label="Amount to Add/Deduct (₦)" type="number" value={salaryForm.amount_change} onChange={ev=>setSF(p=>({...p,amount_change:ev.target.value}))}/>
              <Inp label="Effective Date" type="date" value={salaryForm.effective_date} onChange={ev=>setSF(p=>({...p,effective_date:ev.target.value}))} required/>
              <Txt label="Reason" value={salaryForm.reason} onChange={ev=>setSF(p=>({...p,reason:ev.target.value}))}/>
              <div className="flex justify-end gap-2">
                <button type="button" onClick={()=>setModal(null)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2 text-white rounded-xl text-sm font-semibold" style={{background:salaryForm.type==='fine'?'#ef4444':BRAND}}>{saving?'Saving…':'Apply'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Event Modal */}
      {modal==='event'&&(
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setModal(null)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md" onClick={ev=>ev.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b"><h3 className="font-bold text-gray-900 capitalize">Record {eventForm.type.replace(/_/g,' ')}</h3><button onClick={()=>setModal(null)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button></div>
            <form onSubmit={submitEvent} className="p-5 space-y-4">
              <Sel label="Event Type" value={eventForm.type} onChange={ev=>setEF(p=>({...p,type:ev.target.value}))}>
                <option value="award">Award</option>
                <option value="review">Review</option>
                <option value="fine">Fine</option>
                <option value="department_change">Department Change</option>
                <option value="status_change">Status Change</option>
                <option value="note">Note</option>
                <option value="termination">Termination</option>
              </Sel>
              <Inp label="Title / Description" value={eventForm.title} onChange={ev=>setEF(p=>({...p,title:ev.target.value}))} required/>
              {eventForm.type==='fine'&&<Inp label="Amount (₦)" type="number" value={eventForm.amount} onChange={ev=>setEF(p=>({...p,amount:ev.target.value}))} min="0"/>}
              {eventForm.type==='status_change'&&(
                <Sel label="New Status" value={eventForm.new_value} onChange={ev=>setEF(p=>({...p,new_value:ev.target.value}))}>
                  <option value="">Select…</option>
                  {['active','on-leave','terminated','resigned'].map(s=><option key={s} value={s}>{s}</option>)}
                </Sel>
              )}
              {eventForm.type==='department_change'&&(
                <Sel label="New Department" value={eventForm.new_value} onChange={ev=>setEF(p=>({...p,new_value:ev.target.value}))}>
                  <option value="">Select…</option>
                  {departments.map(d=><option key={d.id} value={d.name}>{d.name}</option>)}
                </Sel>
              )}
              <Inp label="Date" type="date" value={eventForm.event_date} onChange={ev=>setEF(p=>({...p,event_date:ev.target.value}))} required/>
              <Txt label="Notes" value={eventForm.description} onChange={ev=>setEF(p=>({...p,description:ev.target.value}))}/>
              <div className="flex justify-end gap-2">
                <button type="button" onClick={()=>setModal(null)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2 text-white rounded-xl text-sm font-semibold" style={{background:BRAND}}>{saving?'Saving…':'Record'}</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

