import React, { useEffect, useState, useMemo } from 'react';
import {
  AreaChart, Area, BarChart, Bar,
  XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, LineChart, Line, Legend,
} from 'recharts';
import { Link } from 'react-router-dom';
import { dashboardService } from '../../services/projects.service';
import { MOCK_TASKS, MOCK_PROJECTS, getAllProjects, getAllTasks, getProjectById, getTasksForProject } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';
import { usePermissions } from '../../context/PermissionsContext';

// ── Static mock data ───────────────────────────────────────────────────────
const ACTIVITY = [
  { id: 1, user: 'Ana T.',    action: 'actualizó estado de tarea', target: 'Migración datos históricos', time: 'hace 3 min',  dot: 'bg-blue-500' },
  { id: 2, user: 'Luis M.',   action: 'completó',                  target: 'Diseño arquitectura BD',     time: 'hace 18 min', dot: 'bg-emerald-500' },
  { id: 3, user: 'Carlos R.', action: 'comentó en',                target: 'Integración WMS externo',    time: 'hace 42 min', dot: 'bg-purple-500' },
  { id: 4, user: 'Admin S.',  action: 'creó proyecto',             target: 'AR-ProjectManagement "Horizontes"', time: 'hace 2 h',    dot: 'bg-amber-500' },
  { id: 5, user: 'Ana T.',    action: 'bloqueó tarea',             target: 'Testing módulo compras',     time: 'hace 3 h',    dot: 'bg-red-500' },
];

const BUDGET = [
  { name: 'AR-ProjectManagement', budget: 15000000, spent: 1875000, pct: 12.5, color: '#2563EB' },
  { name: 'AR-ProjectManagement',   budget: 800000,   spent: 384000,  pct: 48.0, color: '#EF4444' },
  { name: 'Álbum Horizontes',  budget: 250000,   spent: 87500,   pct: 35.0, color: '#F59E0B' },
];

const MONTH_LABELS = ['E','F','M','A','M','J','J','A','S','O','N','D'];

function buildMonthly(tasks) {
  const byMonth = {};
  tasks.filter(t => !t.isMilestone && t.dueDate).forEach(t => {
    const d = new Date(t.dueDate);
    const key = `${d.getFullYear()}-${d.getMonth()}`;
    if (!byMonth[key]) byMonth[key] = { year: d.getFullYear(), month: d.getMonth(), done: 0, open: 0 };
    if (t.status === 'COMPLETADA') byMonth[key].done++;
    else byMonth[key].open++;
  });
  return Object.values(byMonth)
    .sort((a, b) => a.year !== b.year ? a.year - b.year : a.month - b.month)
    .map(r => ({ m: MONTH_LABELS[r.month], done: r.done, open: r.open, _key: `${r.year}-${r.month}` }));
}

const SPARKS = {
  active:  [2,3,3,4,4,5,6],
  risk:    [0,1,1,1,2,1,1],
  done:    [8,14,22,31,39,47,52],
  members: [5,5,6,6,7,7,7],
};

// ── Helpers ────────────────────────────────────────────────────────────────
const fmtMoney = n =>
  n >= 1_000_000 ? `$${(n/1_000_000).toFixed(1)}M`
  : n >= 1000    ? `$${(n/1000).toFixed(0)}K`
  : `$${n}`;

const RAG_CFG = {
  VERDE:    { dot: 'bg-emerald-400', text: 'text-emerald-600 dark:text-emerald-400', label: 'Verde' },
  AMARILLO: { dot: 'bg-amber-400',   text: 'text-amber-600 dark:text-amber-400',     label: 'Ámbar' },
  ROJO:     { dot: 'bg-red-400',     text: 'text-red-600 dark:text-red-400',          label: 'Rojo'  },
};

// Compromisos simulados: OTs + OCs aprobadas con costo
const MOCK_COMPROMISOS = [
  { id:'OT-001', tipo:'Orden de Trabajo', desc:'Excavación Lote B',         monto:18500000, proyecto:'AR-ProjectManagement', fecha:'2026-07-15' },
  { id:'OT-003', tipo:'Orden de Trabajo', desc:'Instalación eléctrica',     monto:12000000, proyecto:'AR-ProjectManagement', fecha:'2026-07-22' },
  { id:'OC-042', tipo:'Orden de Compra',  desc:'Acero estructural 40T',     monto:34000000, proyecto:'AR-ProjectManagement', fecha:'2026-08-05' },
  { id:'OC-051', tipo:'Orden de Compra',  desc:'Licencias SQL Server',      monto:4200000,  proyecto:'AR-ProjectManagement',   fecha:'2026-07-30' },
];
// Flujo de caja registrado por proyecto (0 = sin flujo registrado)
const MOCK_FLUJO_CAJA = {
  'AR-ProjectManagement': 15000000,
  'AR-ProjectManagement':   0,
};

// Destinatarios fijos de alertas financieras
const FINANCE_RECIPIENTS = [
  { id:'r1', name:'Álvaro Romero',    role:'Dueño / CEO',             avatar:'AR', color:'bg-slate-700' },
  { id:'r2', name:'Paula Soto',       role:'Gerente de Proyecto',     avatar:'AT', color:'bg-blue-600'  },
  { id:'r3', name:'María Jiménez',    role:'Directora Financiera',    avatar:'MJ', color:'bg-purple-600'},
  { id:'r4', name:'Carlos Ríos',      role:'Jefe de Contaduría',      avatar:'CR', color:'bg-emerald-600'},
];

const STORAGE_KEY = 'arpm_cashflow_notifications';

function loadNotified() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); }
  catch { return []; }
}
function saveNotified(ids) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(ids));
}

function NotifyModal({ alarmas, onClose, onSent }) {
  const [sent, setSent] = useState(false);
  const fmtM = n => n >= 1_000_000 ? `$${(n/1_000_000).toFixed(1)}M` : `$${(n/1000).toFixed(0)}K`;
  const totalDeficit = alarmas.reduce((s,a) => s + a.deficit, 0);
  const urgente = alarmas.slice().sort((a,b) => new Date(a.fecha)-new Date(b.fecha))[0];

  const handleSend = () => {
    setSent(true);
    setTimeout(() => { onSent(); onClose(); }, 1800);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-lg border border-slate-200 dark:border-surface-700" onClick={e=>e.stopPropagation()}>
        <div className="flex items-center gap-3 px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <div className="w-8 h-8 rounded-lg bg-red-600 flex items-center justify-center flex-shrink-0">
            <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>
          </div>
          <div>
            <h2 className="text-sm font-bold text-slate-900 dark:text-white">Notificar alerta de flujo de caja</h2>
            <p className="text-xs text-slate-400 mt-0.5">{alarmas.length} compromiso{alarmas.length>1?'s':''} sin cobertura · Déficit total {fmtM(totalDeficit)}</p>
          </div>
        </div>

        <div className="p-6 space-y-4">
          {/* Vista previa del mensaje */}
          <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-200 dark:border-surface-600 text-xs space-y-2">
            <p className="font-bold text-slate-700 dark:text-gray-200">⚠ ALERTA — Déficit de Flujo de Caja</p>
            <p className="text-slate-600 dark:text-gray-300">Se han detectado <strong>{alarmas.length} compromiso{alarmas.length>1?'s':''}</strong> de pago sin cobertura de flujo de caja por un total de <strong>{fmtM(totalDeficit)}</strong>.</p>
            <div className="border-t border-slate-200 dark:border-surface-600 pt-2 space-y-1">
              {alarmas.map(a => (
                <p key={a.id} className="text-slate-500 dark:text-gray-400">
                  · <span className="font-mono font-semibold text-slate-700 dark:text-gray-300">{a.id}</span> {a.desc} — {a.proyecto} — Déficit: <span className="font-bold text-red-600 dark:text-red-400">{fmtM(a.deficit)}</span> — Vence: {new Date(a.fecha).toLocaleDateString('es-CO',{day:'2-digit',month:'short'})}
                </p>
              ))}
            </div>
            {urgente && (
              <p className="text-red-600 dark:text-red-400 font-semibold border-t border-slate-200 dark:border-surface-600 pt-2">
                Compromiso más urgente: {urgente.id} — vence el {new Date(urgente.fecha).toLocaleDateString('es-CO',{day:'2-digit',month:'long',year:'numeric'})}
              </p>
            )}
            <p className="text-slate-400 dark:text-gray-500 border-t border-slate-200 dark:border-surface-600 pt-2">Acción requerida: registrar flujo de caja en módulo EVM o gestionar disponibilidad con el área financiera.</p>
          </div>

          {/* Destinatarios */}
          <div>
            <p className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide mb-2">Se notificará a</p>
            <div className="grid grid-cols-2 gap-2">
              {FINANCE_RECIPIENTS.map(r => (
                <div key={r.id} className="flex items-center gap-2.5 p-2.5 rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700">
                  <div className={`w-7 h-7 rounded-full ${r.color} flex items-center justify-center flex-shrink-0`}>
                    <span className="text-white text-xs font-bold">{r.avatar}</span>
                  </div>
                  <div>
                    <p className="text-xs font-semibold text-slate-800 dark:text-white leading-tight">{r.name}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500 leading-tight">{r.role}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="flex justify-end gap-2 px-6 py-4 border-t border-slate-100 dark:border-surface-700">
          <button onClick={onClose} className="px-4 py-2 text-sm text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 rounded-lg cursor-pointer transition-colors">Cancelar</button>
          <button onClick={handleSend} disabled={sent}
            className={`px-4 py-2 text-sm font-semibold rounded-lg cursor-pointer flex items-center gap-2 transition-all ${sent ? 'bg-emerald-600 text-white' : 'bg-red-600 hover:bg-red-700 text-white'}`}>
            {sent
              ? <><svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>Enviado</>
              : <><svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>Enviar notificación</>
            }
          </button>
        </div>
      </div>
    </div>
  );
}

function CashFlowAlarms() {
  const [dismissed, setDismissed]   = useState([]);
  const [notified, setNotified]     = useState(loadNotified);
  const [showModal, setShowModal]   = useState(false);
  const [justSent, setJustSent]     = useState(false);

  const fmtDate = d => new Date(d).toLocaleDateString('es-CO', { day:'2-digit', month:'short', year:'numeric' });
  const fmtM    = n => n >= 1_000_000 ? `$${(n/1_000_000).toFixed(1)}M` : `$${(n/1000).toFixed(0)}K`;

  const alarmas = MOCK_COMPROMISOS
    .filter(c => !dismissed.includes(c.id))
    .map(c => {
      const flujo   = MOCK_FLUJO_CAJA[c.proyecto] ?? 0;
      const cubierto = flujo >= c.monto;
      return { ...c, flujo, cubierto, deficit: Math.max(0, c.monto - flujo) };
    })
    .filter(c => !c.cubierto);

  if (!alarmas.length) return null;

  const totalDeficit    = alarmas.reduce((s, a) => s + a.deficit, 0);
  const alreadyNotified = alarmas.every(a => notified.includes(a.id));

  const handleSent = () => {
    const ids = [...new Set([...notified, ...alarmas.map(a=>a.id)])];
    setNotified(ids);
    saveNotified(ids);
    setJustSent(true);
    setTimeout(() => setJustSent(false), 5000);
  };

  return (
    <>
    <div className="rounded-2xl border-2 border-red-200 dark:border-red-500/30 bg-red-50 dark:bg-red-500/5 p-4 space-y-3">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="w-9 h-9 rounded-xl bg-red-600 flex items-center justify-center flex-shrink-0 animate-pulse">
          <svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
          </svg>
        </div>
        <div className="flex-1">
          <p className="text-sm font-bold text-red-800 dark:text-red-300">
            Alerta de flujo de caja — {alarmas.length} compromiso{alarmas.length > 1 ? 's' : ''} sin cobertura
          </p>
          <p className="text-xs text-red-600 dark:text-red-400 mt-0.5">
            Déficit total: <span className="font-bold">{fmtM(totalDeficit)}</span>
          </p>
        </div>
        {/* Botón notificar */}
        <div className="flex items-center gap-2 flex-shrink-0">
          {justSent && (
            <span className="text-xs font-semibold text-emerald-600 dark:text-emerald-400 flex items-center gap-1">
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>
              Notificados
            </span>
          )}
          <button onClick={() => setShowModal(true)}
            className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold rounded-lg cursor-pointer transition-all ${
              alreadyNotified
                ? 'bg-slate-200 dark:bg-surface-600 text-slate-500 dark:text-gray-400'
                : 'bg-red-600 hover:bg-red-700 text-white shadow-sm'
            }`}>
            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>
            {alreadyNotified ? 'Ya notificado' : 'Notificar'}
          </button>
        </div>
      </div>

      {/* Destinatarios (resumen compacto) */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-xs text-red-500 dark:text-red-400 font-semibold">Se notifica a:</span>
        {FINANCE_RECIPIENTS.map(r => (
          <span key={r.id} className={`flex items-center gap-1.5 text-xs px-2 py-0.5 rounded-full text-white font-medium ${r.color}`}>
            {r.avatar} · {r.role}
          </span>
        ))}
      </div>

      {/* Tabla */}
      <div className="overflow-x-auto rounded-xl border border-red-100 dark:border-red-500/20">
        <table className="w-full text-xs">
          <thead>
            <tr className="bg-red-100 dark:bg-red-500/10 text-red-700 dark:text-red-400">
              <th className="px-3 py-2 text-left font-semibold">ID</th>
              <th className="px-3 py-2 text-left font-semibold">Descripción</th>
              <th className="px-3 py-2 text-left font-semibold">Proyecto</th>
              <th className="px-3 py-2 text-right font-semibold">Compromiso</th>
              <th className="px-3 py-2 text-right font-semibold">Flujo caja</th>
              <th className="px-3 py-2 text-right font-semibold">Déficit</th>
              <th className="px-3 py-2 text-left font-semibold">Vence</th>
              <th className="px-3 py-2 text-center font-semibold">Notif.</th>
              <th className="px-3 py-2"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-red-50 dark:divide-red-500/10">
            {alarmas.map(a => (
              <tr key={a.id} className="bg-white dark:bg-surface-800 hover:bg-red-50 dark:hover:bg-red-500/5">
                <td className="px-3 py-2 font-mono font-bold text-slate-600 dark:text-gray-300">{a.id}</td>
                <td className="px-3 py-2 text-slate-700 dark:text-gray-300">{a.desc}</td>
                <td className="px-3 py-2 text-slate-500 dark:text-gray-400">{a.proyecto}</td>
                <td className="px-3 py-2 text-right font-bold text-slate-800 dark:text-white tabular-nums">{fmtM(a.monto)}</td>
                <td className="px-3 py-2 text-right tabular-nums text-slate-500 dark:text-gray-400">
                  {a.flujo ? fmtM(a.flujo) : <span className="text-red-500 font-semibold">Sin registro</span>}
                </td>
                <td className="px-3 py-2 text-right font-bold text-red-600 dark:text-red-400 tabular-nums">{fmtM(a.deficit)}</td>
                <td className="px-3 py-2 text-slate-500 dark:text-gray-400 whitespace-nowrap">{fmtDate(a.fecha)}</td>
                <td className="px-3 py-2 text-center">
                  {notified.includes(a.id)
                    ? <span title="Notificado" className="text-emerald-500">
                        <svg className="w-4 h-4 inline" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                      </span>
                    : <span title="Pendiente de notificar" className="text-amber-400">
                        <svg className="w-4 h-4 inline" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                      </span>
                  }
                </td>
                <td className="px-3 py-2">
                  <button onClick={() => setDismissed(d => [...d, a.id])}
                    title="Descartar alerta"
                    className="text-red-300 hover:text-red-500 cursor-pointer transition-colors">
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>

    {showModal && (
      <NotifyModal
        alarmas={alarmas}
        onClose={() => setShowModal(false)}
        onSent={handleSent}
      />
    )}
    </>
  );
}

const STATUS_BADGE = {
  ACTIVO:     'bg-blue-100 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400',
  EN_RIESGO:  'bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-400',
  COMPLETADO: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400',
  PAUSADO:    'bg-slate-100 text-slate-600 dark:bg-gray-500/10 dark:text-gray-400',
};

// ── Sub-components ─────────────────────────────────────────────────────────
function Sparkline({ data, color }) {
  return (
    <ResponsiveContainer width={64} height={28}>
      <LineChart data={data.map((v, i) => ({ v, i }))}>
        <Line type="monotone" dataKey="v" stroke={color} strokeWidth={1.5} dot={false}/>
      </LineChart>
    </ResponsiveContainer>
  );
}

function KPICard({ label, value, sub, trend, trendUp, sparkData, sparkColor, loading }) {
  return (
    <div className="bg-white dark:bg-surface-800 rounded-2xl p-5
      border border-slate-200 dark:border-surface-700
      hover:border-slate-300 dark:hover:border-surface-600
      shadow-sm hover:shadow-md transition-all cursor-default">
      {loading ? (
        <div className="animate-pulse space-y-3">
          <div className="h-3 w-20 bg-slate-100 dark:bg-surface-700 rounded"/>
          <div className="h-7 w-14 bg-slate-100 dark:bg-surface-700 rounded"/>
        </div>
      ) : (
        <div className="flex items-start justify-between gap-2">
          <div>
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-widest mb-1.5">{label}</p>
            <p className="text-3xl font-bold text-slate-900 dark:text-white tabular-nums">{value}</p>
            <div className="flex items-center gap-1.5 mt-2">
              {trend !== undefined && (
                <span className={`text-xs font-semibold flex items-center gap-0.5 ${trendUp ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>
                  <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                    <path strokeLinecap="round" strokeLinejoin="round" d={trendUp ? 'M5 15l7-7 7 7' : 'M19 9l-7 7-7-7'}/>
                  </svg>
                  {trend}
                </span>
              )}
              {sub && <span className="text-xs text-slate-400 dark:text-gray-500">{sub}</span>}
            </div>
          </div>
          {sparkData && <Sparkline data={sparkData} color={sparkColor}/>}
        </div>
      )}
    </div>
  );
}

const TT_LIGHT = { background:'#fff', border:'1px solid #e2e8f0', borderRadius:8, fontSize:12, color:'#0f172a' };

// ── Mock data for new widgets ──────────────────────────────────────────────

const BURNDOWN_DATA = [
  { week:'Sem 1', 'PRY-2026-004':18, 'PRY-2026-004':12, 'PRY-2026-004':22, 'PRY-2026-004':9  },
  { week:'Sem 2', 'PRY-2026-004':21, 'PRY-2026-004':15, 'PRY-2026-004':20, 'PRY-2026-004':14 },
  { week:'Sem 3', 'PRY-2026-004':17, 'PRY-2026-004':11, 'PRY-2026-004':17, 'PRY-2026-004':18 },
  { week:'Sem 4', 'PRY-2026-004':24, 'PRY-2026-004':18, 'PRY-2026-004':14, 'PRY-2026-004':22 },
  { week:'Sem 5', 'PRY-2026-004':19, 'PRY-2026-004':22, 'PRY-2026-004':11, 'PRY-2026-004':25 },
  { week:'Sem 6', 'PRY-2026-004':28, 'PRY-2026-004':14, 'PRY-2026-004': 8, 'PRY-2026-004':21 },
  { week:'Sem 7', 'PRY-2026-004':22, 'PRY-2026-004':19, 'PRY-2026-004': 6, 'PRY-2026-004':29 },
  { week:'Sem 8', 'PRY-2026-004':31, 'PRY-2026-004':16, 'PRY-2026-004': 4, 'PRY-2026-004':33 },
];

const RESOURCE_PEOPLE = ['Paula Soto','Luis Mora','Carlos Ríos','María J.','Pedro S.','Laura V.'];
const RESOURCE_DAYS   = ['Lun','Mar','Mié','Jue','Vie'];
const RESOURCE_DATA   = [
  [95, 80, 60, 110, 45],
  [70, 55, 90, 75, 100],
  [40, 115, 85, 50, 70],
  [60, 70, 45, 90, 80],
  [105, 65, 75, 55, 95],
  [50, 90, 100, 80, 60],
];

function utilizationClass(pct) {
  if (pct > 100) return 'bg-red-100 dark:bg-red-900/20 text-red-700 dark:text-red-400 font-bold';
  if (pct >= 80) return 'bg-amber-100 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400';
  if (pct >= 50) return 'bg-blue-100 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400';
  return 'bg-emerald-100 dark:bg-emerald-900/20 text-emerald-700 dark:text-emerald-400';
}

const MILESTONES = [
  { id:'m1', date:'2026-07-03', name:'Entrega diseño estructural',        projectId:'p4', code:'PRY-2026-004', responsible:'Paula Soto',  rag:'VERDE'    },
  { id:'m2', date:'2026-07-08', name:'Mezcla final álbum',               projectId:'p4', code:'PRY-2026-004', responsible:'Luis Mora',    rag:'AMARILLO' },
  { id:'m3', date:'2026-07-15', name:'Go-live módulo compras ERP',       projectId:'p4', code:'PRY-2026-004', responsible:'Carlos Ríos',  rag:'ROJO'     },
  { id:'m4', date:'2026-07-20', name:'Release v1.0 AR-PM',               projectId:'p4', code:'PRY-2026-004', responsible:'María J.',     rag:'VERDE'    },
  { id:'m5', date:'2026-07-25', name:'Auditoría presupuestal Q2',        projectId:'p4', code:'PRY-2026-004', responsible:'Pedro S.',     rag:'AMARILLO' },
  { id:'m6', date:'2026-07-28', name:'Lanzamiento distribución digital', projectId:'p4', code:'PRY-2026-004', responsible:'Laura V.',     rag:'VERDE'    },
];

const PROJECT_BADGE_COLOR = {
  'PRY-2026-004': 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
  'PRY-2026-004': 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300',
  'PRY-2026-004': 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
  'PRY-2026-004': 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300',
};

const RAG_DOT = {
  VERDE:    'bg-emerald-400',
  AMARILLO: 'bg-amber-400',
  ROJO:     'bg-red-500',
};

// ── New sub-components ─────────────────────────────────────────────────────

function BurndownWidget() {
  return (
    <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
      <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">
        Velocidad del Portafolio — Últimas 8 semanas
      </p>
      <ResponsiveContainer width="100%" height={220}>
        <LineChart data={BURNDOWN_DATA} margin={{top:4,right:8,left:-20,bottom:0}}>
          <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
          <XAxis dataKey="week" tick={{fill:'#94a3b8',fontSize:11}} axisLine={false} tickLine={false}/>
          <YAxis tick={{fill:'#94a3b8',fontSize:11}} axisLine={false} tickLine={false}/>
          <Tooltip contentStyle={TT_LIGHT}/>
          <Legend iconType="circle" iconSize={8} wrapperStyle={{fontSize:11,paddingTop:8}}/>
          <Line type="monotone" dataKey="PRY-2026-004" name="PRY-2026-004" stroke="#3b82f6"  strokeWidth={2} dot={false}/>
          <Line type="monotone" dataKey="PRY-2026-004" name="PRY-2026-004" stroke="#8b5cf6"  strokeWidth={2} dot={false}/>
          <Line type="monotone" dataKey="PRY-2026-004" name="PRY-2026-004" stroke="#ef4444"  strokeWidth={2} dot={false} strokeDasharray="4 2"/>
          <Line type="monotone" dataKey="PRY-2026-004" name="PRY-2026-004" stroke="#10b981"  strokeWidth={2} dot={false}/>
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

function ResourceHeatmap() {
  return (
    <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
      <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">
        Utilización de Recursos — Semana Actual
      </p>
      <div className="overflow-x-auto">
        <table className="w-full text-xs border-separate border-spacing-1">
          <thead>
            <tr>
              <th className="text-left text-slate-400 dark:text-slate-500 font-semibold uppercase px-2 py-1 w-28">Recurso</th>
              {RESOURCE_DAYS.map(d => (
                <th key={d} className="text-center text-slate-400 dark:text-slate-500 font-semibold uppercase px-2 py-1">{d}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {RESOURCE_PEOPLE.map((person, ri) => (
              <tr key={person}>
                <td className="text-slate-600 dark:text-slate-300 font-medium px-2 py-1 whitespace-nowrap">{person}</td>
                {RESOURCE_DATA[ri].map((pct, ci) => (
                  <td key={ci} className={`text-center rounded-lg px-2 py-1.5 tabular-nums ${utilizationClass(pct)}`}>
                    {pct}%
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="flex flex-wrap gap-3 mt-4 pt-3 border-t border-slate-100 dark:border-surface-700">
        {[
          {cls:'bg-emerald-100 dark:bg-emerald-900/20 text-emerald-700 dark:text-emerald-400', label:'<50% — Disponible'},
          {cls:'bg-blue-100 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400',             label:'50–80% — Normal'},
          {cls:'bg-amber-100 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400',         label:'80–100% — Alto'},
          {cls:'bg-red-100 dark:bg-red-900/20 text-red-700 dark:text-red-400 font-bold',       label:'>100% — Sobre-asignado'},
        ].map(({cls, label}) => (
          <span key={label} className={`text-xs px-2.5 py-0.5 rounded-full ${cls}`}>{label}</span>
        ))}
      </div>
    </div>
  );
}

function MilestonesWidget({ selectedProjectId: spid }) {
  const today = new Date('2026-06-26');
  const milestones = MILESTONES
    .filter(m => !spid || m.projectId === spid)
    .map(m => {
      const mDate = new Date(m.date);
      const diff  = Math.round((mDate - today) / 86400000);
      return { ...m, diff };
    })
    .sort((a, b) => a.diff - b.diff);

  const daysColor = d => d <= 7 ? 'text-red-600 dark:text-red-400 font-bold' : d <= 14 ? 'text-amber-600 dark:text-amber-400 font-semibold' : 'text-emerald-600 dark:text-emerald-400';

  return (
    <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
      <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">
        Próximos Hitos — 30 días
      </p>
      <div className="space-y-3">
        {milestones.map(m => (
          <div key={m.id} className="flex items-start gap-3 py-2 border-b border-slate-50 dark:border-surface-700 last:border-0">
            <span className={`w-2.5 h-2.5 rounded-full flex-shrink-0 mt-1 ${RAG_DOT[m.rag]}`}/>
            <div className="flex-1 min-w-0">
              <div className="flex flex-wrap items-center gap-2 mb-0.5">
                <p className="text-xs font-medium text-slate-800 dark:text-white truncate">{m.name}</p>
                <span className={`text-xs px-2 py-0.5 rounded-full font-medium flex-shrink-0 ${PROJECT_BADGE_COLOR[m.code]}`}>{m.code}</span>
              </div>
              <div className="flex items-center gap-3 text-xs text-slate-400 dark:text-slate-500">
                <span>{new Date(m.date).toLocaleDateString('es-CO',{day:'2-digit',month:'short'})}</span>
                <span>·</span>
                <span>{m.responsible}</span>
                <span>·</span>
                <span className={daysColor(m.diff)}>
                  {m.diff <= 0 ? 'Hoy / vencido' : `en ${m.diff} días`}
                </span>
              </div>
            </div>
          </div>
        ))}
        {milestones.length === 0 && (
          <p className="text-xs text-slate-400 dark:text-slate-500 text-center py-4">Sin hitos próximos para este proyecto.</p>
        )}
      </div>
    </div>
  );
}

function QuickActions() {
  const actions = [
    { label:'Nueva Tarea',       to:'/projects',      color:'bg-blue-600 hover:bg-blue-700',   icon:'M12 4v16m8-8H4' },
    { label:'Registrar Horas',   to:'/time-tracking', color:'bg-purple-600 hover:bg-purple-700', icon:'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z' },
    { label:'Ver Portafolio',    to:'/portfolio',     color:'bg-teal-600 hover:bg-teal-700',   icon:'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z' },
    { label:'Nuevo Riesgo',      to:'/risks',         color:'bg-red-600 hover:bg-red-700',     icon:'M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z' },
    { label:'Standup Hoy',       to:'/standup',       color:'bg-amber-500 hover:bg-amber-600', icon:'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z' },
  ];
  return (
    <div className="bg-white dark:bg-surface-800 rounded-2xl p-4 border border-slate-200 dark:border-surface-700 shadow-sm">
      <p className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-widest mb-3">Acciones rápidas</p>
      <div className="flex flex-wrap gap-2">
        {actions.map(({ label, to, color, icon }) => (
          <Link key={to} to={to}
            className={`inline-flex items-center gap-2 ${color} text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors`}>
            <svg className="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d={icon}/>
            </svg>
            {label}
          </Link>
        ))}
      </div>
    </div>
  );
}

export default function Dashboard() {
  const { selectedProjectId } = useProject();
  const { can }               = usePermissions();
  const [kpis, setKpis]       = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    dashboardService.getKPIs()
      .then(d => setKpis(d))
      .catch(() => setKpis(null))
      .finally(() => setLoading(false));
  }, []);

  // Compute velocity from real task data, filtered by selected project
  const monthly = useMemo(() => {
    const allTasks = selectedProjectId
      ? getTasksForProject(selectedProjectId)
      : Object.values(getAllTasks()).flat();
    return buildMonthly(allTasks);
  }, [selectedProjectId]);

  // KPI counts from filtered tasks
  const taskStats = useMemo(() => {
    const tasks = selectedProjectId
      ? getTasksForProject(selectedProjectId)
      : Object.values(getAllTasks()).flat();
    return tasks.reduce((acc, t) => {
      acc[t.status] = (acc[t.status] || 0) + 1;
      return acc;
    }, {});
  }, [selectedProjectId]);

  const projects = useMemo(() => {
    const all = kpis?.recentProjects ?? [];
    return selectedProjectId ? all.filter(p => p.id === selectedProjectId) : all;
  }, [kpis, selectedProjectId]);

  const selectedProject = selectedProjectId
    ? getProjectById(selectedProjectId)
    : null;

  return (
    <div className="space-y-5 pb-6">

      {/* KPI row */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
        <KPICard label="Proyectos activos"  value={kpis?.projectsByStatus?.ACTIVO ?? '—'}     sub="vs mes anterior"  trend="+1"         trendUp sparkData={SPARKS.active}  sparkColor="#2563EB" loading={loading}/>
        <KPICard label="En riesgo"           value={kpis?.projectsByStatus?.EN_RIESGO ?? '—'}  sub="requieren atención" trend="sin cambio" trendUp={false} sparkData={SPARKS.risk}  sparkColor="#EF4444" loading={loading}/>
        <KPICard label="Tareas completadas"  value={taskStats.COMPLETADA ?? '—'}               sub="este período"     trend={selectedProjectId ? null : '+13'} trendUp sparkData={SPARKS.done}   sparkColor="#10B981" loading={loading}/>
        <KPICard label="Miembros activos"    value={kpis?.activeUsers ?? '—'}                  sub="en plataforma"    trend="+1"         trendUp sparkData={SPARKS.members} sparkColor="#8B5CF6" loading={loading}/>
      </div>

      {/* Quick Actions */}
      <QuickActions />

      {/* ── Alarmas de flujo de caja — solo roles financieros ── */}
      {can('CASH_FLOW_ALARM') && <CashFlowAlarms />}

      {/* Multi-project Burndown */}
      <BurndownWidget />

      {/* Resource heatmap + Milestones */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
        <ResourceHeatmap />
        <MilestonesWidget selectedProjectId={selectedProjectId} />
      </div>

      {/* Charts row */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">

        {/* Area chart */}
        <div className="xl:col-span-2 bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
          <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">
            Velocidad del equipo — tareas por mes
            {selectedProject && <span className="ml-2 text-xs font-normal text-blue-500">({selectedProject.code})</span>}
          </p>
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={monthly} margin={{top:4,right:4,left:-20,bottom:0}}>
              <defs>
                <linearGradient id="gDone" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#10B981" stopOpacity={0.2}/>
                  <stop offset="100%" stopColor="#10B981" stopOpacity={0}/>
                </linearGradient>
                <linearGradient id="gOpen" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#2563EB" stopOpacity={0.15}/>
                  <stop offset="100%" stopColor="#2563EB" stopOpacity={0}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
              <XAxis dataKey="m" tick={{fill:'#94a3b8',fontSize:11}} axisLine={false} tickLine={false}/>
              <YAxis tick={{fill:'#94a3b8',fontSize:11}} axisLine={false} tickLine={false}/>
              <Tooltip contentStyle={TT_LIGHT}/>
              <Area type="monotone" dataKey="done" name="Completadas" stroke="#10B981" fill="url(#gDone)" strokeWidth={2}/>
              <Area type="monotone" dataKey="open" name="Abiertas"    stroke="#2563EB" fill="url(#gOpen)" strokeWidth={2}/>
            </AreaChart>
          </ResponsiveContainer>
          <div className="flex gap-4 mt-2">
            {[{c:'#10B981',l:'Completadas'},{c:'#2563EB',l:'Abiertas'}].map(({c,l})=>(
              <span key={l} className="flex items-center gap-1.5 text-xs text-slate-400 dark:text-gray-500">
                <span className="w-2 h-2 rounded-full" style={{background:c}}/>{l}
              </span>
            ))}
          </div>
        </div>

        {/* Bar */}
        <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
          <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">Estado de tareas</p>
          <ResponsiveContainer width="100%" height={170}>
            <BarChart
              data={Object.entries(
                  Object.keys(taskStats).length ? taskStats : {PENDIENTE:12,EN_PROCESO:8,COMPLETADA:24,BLOQUEADA:3}
                ).map(([k,v])=>({name:k.replace(/_/g,' '),v}))}
              layout="vertical" margin={{top:0,right:8,left:0,bottom:0}}
            >
              <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" horizontal={false}/>
              <XAxis type="number" tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false}/>
              <YAxis type="category" dataKey="name" tick={{fill:'#64748b',fontSize:10}} axisLine={false} tickLine={false} width={80}/>
              <Tooltip contentStyle={TT_LIGHT}/>
              <Bar dataKey="v" name="Tareas" fill="#2563EB" radius={[0,4,4,0]}
                background={{fill:'#f1f5f9',radius:[0,4,4,0]}}/>
            </BarChart>
          </ResponsiveContainer>
          <div className="mt-3 grid grid-cols-2 gap-2">
            {[
              {l:'Bloqueadas',   v:taskStats.BLOQUEADA??0,        cls:'text-red-600 dark:text-red-400',    bg:'bg-red-50 dark:bg-red-500/10'},
              {l:'Verificación', v:taskStats.EN_VERIFICACION??0, cls:'text-amber-600 dark:text-amber-400', bg:'bg-amber-50 dark:bg-amber-500/10'},
            ].map(({l,v,cls,bg})=>(
              <div key={l} className={`${bg} rounded-xl p-3`}>
                <p className="text-xs text-slate-500 dark:text-gray-500 mb-0.5">{l}</p>
                <p className={`text-lg font-bold ${cls}`}>{v}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Table + widgets */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">

        {/* Projects table */}
        <div className="xl:col-span-2 bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-slate-100 dark:border-surface-700 flex justify-between items-center">
            <p className="text-sm font-semibold text-slate-800 dark:text-white">Proyectos activos</p>
            <a href="/projects" className="text-xs text-blue-600 dark:text-blue-400 hover:underline cursor-pointer">Ver todos →</a>
          </div>
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100 dark:border-surface-700">
                {['Proyecto','Estado','RAG','Avance','Presupuesto'].map(h=>(
                  <th key={h} className="px-5 py-2.5 text-left text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
              {loading
                ? [1,2,3].map(i=>(
                  <tr key={i}>{[1,2,3,4,5].map(j=>(
                    <td key={j} className="px-5 py-3.5">
                      <div className="h-3 bg-slate-100 dark:bg-surface-700 rounded animate-pulse"/>
                    </td>
                  ))}</tr>
                ))
                : projects.map(p=>{
                  const rag = RAG_CFG[p.ragStatus] || RAG_CFG.VERDE;
                  const pct = p.progressPct ?? 0;
                  const barColor = pct >= 75 ? '#10B981' : pct >= 40 ? '#2563EB' : '#F59E0B';
                  return (
                    <tr key={p.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/50 transition-colors cursor-pointer">
                      <td className="px-5 py-3.5">
                        <p className="text-sm font-medium text-slate-900 dark:text-white truncate max-w-[180px]">{p.name}</p>
                        <p className="text-xs text-slate-400 dark:text-gray-500 font-mono mt-0.5">{p.code}</p>
                      </td>
                      <td className="px-5 py-3.5">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${STATUS_BADGE[p.status] || STATUS_BADGE.ACTIVO}`}>
                          {(p.status||'ACTIVO').replace('_',' ')}
                        </span>
                      </td>
                      <td className="px-5 py-3.5">
                        <span className={`inline-flex items-center gap-1.5 text-xs font-medium ${rag.text}`}>
                          <span className={`w-2 h-2 rounded-full ${rag.dot}`}/>
                          {rag.label}
                        </span>
                      </td>
                      <td className="px-5 py-3.5 min-w-[110px]">
                        <div className="flex items-center gap-2">
                          <div className="flex-1 h-1.5 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
                            <div className="h-full rounded-full" style={{width:`${pct}%`,background:barColor}}/>
                          </div>
                          <span className="text-xs text-slate-700 dark:text-white font-medium w-8 text-right tabular-nums">{pct}%</span>
                        </div>
                      </td>
                      <td className="px-5 py-3.5 text-xs text-slate-500 dark:text-gray-400 font-mono">
                        {p.budget ? fmtMoney(p.budget) : '—'}
                      </td>
                    </tr>
                  );
                })}
            </tbody>
          </table>
        </div>

        {/* Right column */}
        <div className="space-y-4">

          {/* Budget */}
          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">Ejecución presupuestal</p>
            <div className="space-y-4">
              {BUDGET.map(({name,budget,spent,pct,color})=>(
                <div key={name}>
                  <div className="flex justify-between items-baseline mb-1.5">
                    <p className="text-xs text-slate-600 dark:text-gray-300 truncate max-w-[120px]">{name}</p>
                    <span className="text-xs text-slate-400 dark:text-gray-500 tabular-nums ml-2 flex-shrink-0">
                      {fmtMoney(spent)} / {fmtMoney(budget)}
                    </span>
                  </div>
                  <div className="relative h-2 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
                    <div className="absolute inset-y-0 left-0 rounded-full" style={{width:`${pct}%`,background:color}}/>
                  </div>
                  <p className="text-right text-xs mt-1 font-medium" style={{color}}>{pct}% ejecutado</p>
                </div>
              ))}
            </div>
            <div className="mt-4 pt-4 border-t border-slate-100 dark:border-surface-700 flex justify-between text-xs">
              <span className="text-slate-400 dark:text-gray-500">Presupuesto total</span>
              <span className="text-slate-900 dark:text-white font-semibold tabular-nums">
                {fmtMoney(BUDGET.reduce((s,p)=>s+p.budget,0))}
              </span>
            </div>
          </div>

          {/* Activity */}
          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">Actividad reciente</p>
            <div className="space-y-3">
              {ACTIVITY.map(({id,user,action,target,time,dot})=>(
                <div key={id} className="flex gap-3">
                  <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5 ${dot}`}/>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs text-slate-600 dark:text-gray-300 leading-relaxed">
                      <span className="font-medium text-slate-900 dark:text-white">{user}</span>{' '}
                      {action}{' '}
                      <span className="text-blue-600 dark:text-blue-400">{target}</span>
                    </p>
                    <p className="text-xs text-slate-300 dark:text-gray-600 mt-0.5">{time}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
