import { useState, useEffect, useCallback } from 'react';
import api from '../services/api';
import {
  Search, User as UserIcon, ChevronRight,
  X, FileText, Banknote, CreditCard,
  Clock, Filter, Printer,
  MessageSquare, ShieldAlert, CheckCircle2,
  ShieldCheck
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useToast } from '../context/use-toast';
import clsx from 'clsx';
import ClaimModal from '../components/ClaimModal';
import ResolveClaimModal from '../components/ResolveClaimModal';

export default function HistoryPage() {
  const { showToast } = useToast();
  const [loading, setLoading] = useState(false);
  const [items, setItems] = useState<any[]>([]);
  const [cajeros, setCajeros] = useState<any[]>([]);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [showClaimModal, setShowClaimModal] = useState(false);
  const [claims, setClaims] = useState<any[]>([]);
  const [resolvingClaim, setResolvingClaim] = useState<any>(null);
  const [activeDetailTab, setActiveDetailTab] = useState<'info' | 'claims'>('info');

  // Filtros
  const [filters, setFilters] = useState({
    from: new Date().toISOString().split('T')[0],
    to: new Date().toISOString().split('T')[0],
    userId: '',
    query: '',
    source: 'All' // 'All' | 'Web' | 'Mostrador'
  });

  const loadInitialData = async () => {
    try {
      const res = await api.get('/reports/cajeros');
      setCajeros(res.data);
    } catch (e) { console.error(e); }
  };

  const loadHistory = useCallback(async () => {
    setLoading(true);
    try {
      const response = await api.get('/reports/cashier-transactions', {
        params: {
          from: filters.from,
          to: filters.to,
          userId: filters.userId || null
        }
      });
      setItems(response.data.items || []);
    } catch (error) {
      console.error("Error al cargar historial:", error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  useEffect(() => {
    loadInitialData();
    loadHistory();
  }, [loadHistory]);

  const loadItemClaims = async (listingId: number) => {
    try {
      const res = await api.get(`/claims/listing/${listingId}`);
      setClaims(res.data);
    } catch (e) { console.error(e); }
  };

  const handleOpenDetail = async (id: number) => {
    setActiveDetailTab('info');
    try {
      const res = await api.get(`/listings/${id}`);
      setSelectedItem(res.data);
      loadItemClaims(id);
    } catch (e) { console.error(e); }
  };

  const formatLocalTime = (dateString: string) => {
    let isoStr = dateString.replace(" ", "T");
    if (!isoStr.endsWith("Z")) isoStr += "Z";
    return new Date(isoStr).toLocaleTimeString('es-AR', {
      hour: '2-digit', minute: '2-digit', hour12: true,
      timeZone: 'America/Argentina/Buenos_Aires'
    });
  };

  const escapeHTML = (str: string) => {
    return str?.replace(/[&<>"']/g, (m) => ({
      '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
    }[m] || m)) || '';
  };

  const handlePrintDuplicate = () => {
    if (!selectedItem) return;

    const { listing, payments } = selectedItem;
    const printWindow = window.open('', '_blank', 'width=350,height=700');
    if (!printWindow) return;

    const now = new Date();
    const totalWithSurcharges = payments.reduce((sum: number, p: any) => sum + p.amount + p.surcharge, 0);

    const paymentRows = payments.map((p: any) => {
      const methodName = p.paymentMethod === 'Credit' ? p.cardPlan : p.paymentMethod;
      return `
        <tr>
          <td style="padding: 5px 0; border-bottom: 1px solid #ddd;">${methodName}</td>
          <td style="padding: 5px 0; text-align: right; border-bottom: 1px solid #ddd;">$${p.amount.toLocaleString()}</td>
          ${p.surcharge > 0 ? `<td style="padding: 5px 0; text-align: right; border-bottom: 1px solid #ddd; color: #f59e0b;">+$${p.surcharge.toLocaleString()}</td>` : '<td></td>'}
        </tr>
      `;
    }).join('');

    const html = `
      <html>
        <body style="font-family: 'Courier New', monospace; width: 300px; padding: 10px; font-size: 11px;">
          <div style="text-align: center; border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 10px;">
            <h1 style="margin: 0; font-size: 18px;">DIARIO EL DÍA</h1>
            <p style="margin: 2px 0; font-weight: bold; background: #000; color: #fff; display: inline-block; padding: 2px 10px;">*** DUPLICADO ***</p>
            <p style="margin: 5px 0; font-size: 9px;">Original: ${new Date(listing.createdAt).toLocaleString('es-AR')}</p>
            <p style="margin: 2px 0; font-size: 9px;">Re-impresión: ${now.toLocaleString('es-AR')}</p>
          </div>
          <div style="margin-bottom: 10px;">
            <b>AVISO ID:</b> #${listing.id.toString().padStart(6, '0')}<br/>
            <b>RUBRO:</b> ${escapeHTML(listing.categoryName)}<br/>
            <b>ESTADO:</b> ${listing.status}<br/>
          </div>
          <div style="border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 8px 0; margin-bottom: 10px;">
            <b>CUERPO DEL AVISO:</b><br/>
            <p style="text-transform: uppercase; line-height: 1.4;">${escapeHTML(listing.description)}</p>
          </div>
          <table style="width: 100%; font-size: 10px; margin-bottom: 10px;">
            ${paymentRows}
          </table>
          <div style="background: #000; color: #fff; padding: 10px; text-align: center; font-size: 18px; font-weight: bold;">
            TOTAL: $${totalWithSurcharges.toLocaleString()}
          </div>
        </body>
      </html>
    `;

    printWindow.document.write(html);
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => { printWindow.print(); printWindow.close(); }, 250);
    showToast("Duplicado enviado a la cola de impresión", "success");
  };

  return (
    <div className="p-6 flex flex-col gap-6 h-full bg-[#f8fafc] overflow-hidden">

      {/* FILTROS */}
      <div className="bg-white rounded-[2rem] p-6 shadow-xl border border-slate-200 flex-shrink-0">
        <div className="flex justify-between items-center mb-6">
          <div>
            <span className="text-[9px] font-black text-blue-600 uppercase tracking-[0.3em] mb-0.5 block">Auditoría & Consultas</span>
            <h2 className="text-xl font-black text-slate-900 tracking-tight uppercase flex items-center gap-2">
              <span className="bg-slate-900 w-1.5 h-5 rounded-full"></span>
              Historial de Operaciones
            </h2>
          </div>
          <button
            onClick={loadHistory}
            className="bg-blue-600 text-white px-5 py-2.5 rounded-xl font-black text-[10px] uppercase tracking-widest shadow-lg shadow-blue-200 hover:bg-blue-700 transition-all flex items-center gap-2"
          >
            {loading ? <Clock className="animate-spin" size={14} /> : <Filter size={14} />}
            Actualizar Vista
          </button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          <div className="space-y-1.5">
            <label className="text-[9px] font-black text-slate-500 uppercase ml-1">Desde</label>
            <input type="date" value={filters.from} onChange={e => setFilters({ ...filters, from: e.target.value })} className="w-full bg-slate-50 border-2 border-slate-100 rounded-xl p-3 text-xs font-bold text-slate-700 outline-none focus:border-blue-500 transition-all" />
          </div>
          <div className="space-y-1.5">
            <label className="text-[9px] font-black text-slate-500 uppercase ml-1">Hasta</label>
            <input type="date" value={filters.to} onChange={e => setFilters({ ...filters, to: e.target.value })} className="w-full bg-slate-50 border-2 border-slate-100 rounded-xl p-3 text-xs font-bold text-slate-700 outline-none focus:border-blue-500 transition-all" />
          </div>
          <div className="space-y-1.5">
            <label className="text-[9px] font-black text-slate-500 uppercase ml-1">Origen del Aviso</label>
            <div className="flex bg-slate-100 p-1 rounded-xl">
              {['All', 'Mostrador', 'Web'].map(s => (
                <button
                  key={s}
                  onClick={() => setFilters({ ...filters, source: s })}
                  className={clsx(
                    "flex-1 py-2 text-[9px] font-black uppercase rounded-lg transition-all",
                    filters.source === s ? "bg-white text-blue-600 shadow-sm" : "text-slate-400 hover:text-slate-600"
                  )}
                >
                  {s === 'All' ? 'Todos' : s}
                </button>
              ))}
            </div>
          </div>
          <div className="space-y-1.5">
            <label className="text-[9px] font-black text-slate-500 uppercase ml-1">Cajero Responsable</label>
            <select
              value={filters.userId}
              onChange={e => setFilters({ ...filters, userId: e.target.value })}
              className="w-full bg-slate-50 border-2 border-slate-100 rounded-xl p-3 text-xs font-bold text-slate-700 outline-none focus:border-blue-500 transition-all appearance-none"
            >
              <option value="">TODOS LOS CAJEROS</option>
              {cajeros.map((u) => (
                <option key={u.id || u.Id} value={u.id || u.Id}>
                  {(u.username || u.Username || 'Sin Nombre').toUpperCase()}
                </option>
              ))}
            </select>
          </div>
          <div className="space-y-1.5">
            <label className="text-[9px] font-black text-slate-500 uppercase ml-1">Búsqueda Directa</label>
            <div className="relative">
              <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
              <input type="text" placeholder="Título o aviso..." value={filters.query} onChange={e => setFilters({ ...filters, query: e.target.value })} className="w-full bg-slate-50 border-2 border-slate-100 rounded-xl p-3 pl-10 text-xs font-bold text-slate-700 outline-none focus:border-blue-500 transition-all placeholder:text-slate-300" />
            </div>
          </div>
        </div>
      </div>

      {/* TABLA */}
      <div className="flex-1 bg-white rounded-[2rem] shadow-xl border border-slate-200 overflow-hidden flex flex-col min-h-0">
        <div className="overflow-y-auto flex-1 custom-scrollbar">
          <table className="w-full text-left border-collapse">
            <thead className="bg-slate-50 text-slate-500 text-[9px] uppercase font-black tracking-[0.15em] sticky top-0 z-10 border-b border-slate-100 backdrop-blur-md">
              <tr>
                <th className="px-8 py-4">Operación / Fecha</th>
                <th className="px-8 py-4">Detalle del Aviso</th>
                <th className="px-8 py-4 text-center">Cajero</th>
                <th className="px-8 py-4 text-right">Monto Total</th>
                <th className="px-8 py-4"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              <AnimatePresence mode="popLayout">
                {items
                  .filter(i => (filters.source === 'All' || i.source === filters.source))
                  .filter(i => i.title.toLowerCase().includes(filters.query.toLowerCase()))
                  .map((item) => (
                    <motion.tr
                      key={item.id}
                      initial={{ opacity: 0 }} animate={{ opacity: 1 }}
                      className="hover:bg-blue-50/40 transition-all group"
                    >
                      <td className="px-8 py-4">
                        {/* Badge de Origen */}
                        <div className={clsx(
                          "inline-flex px-2 py-0.5 rounded text-[8px] font-black uppercase mb-2",
                          item.source === 'Web' ? "bg-blue-600 text-white shadow-lg shadow-blue-200" : "bg-slate-200 text-slate-600"
                        )}>
                          {item.source}
                        </div>
                        <div className="font-mono text-slate-400 font-bold text-[10px]">#{item.id.toString().padStart(6, '0')}</div>
                        <div className="text-[10px] font-black text-slate-700 mt-1 flex items-center gap-1.5">
                          <Clock size={12} className="text-blue-500" />
                          {new Date(item.date).toLocaleDateString('es-AR')} - {formatLocalTime(item.date)}
                        </div>
                      </td>
                      <td className="px-8 py-4">
                        <div className="flex flex-col">
                          <span className="font-extrabold text-slate-900 uppercase text-xs tracking-tight line-clamp-1 group-hover:text-blue-600 transition-colors">{item.title}</span>
                          <span className="text-[9px] text-slate-500 font-bold uppercase tracking-tighter mt-0.5">{item.category}</span>
                        </div>
                      </td>
                      <td className="px-8 py-4 text-center">
                        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-slate-100 rounded-lg text-[9px] font-black text-slate-600 uppercase border border-slate-200">
                          <UserIcon size={10} className="text-slate-400" /> {item.cashier || 'SISTEMA'}
                        </span>
                      </td>
                      <td className="px-8 py-4 text-right font-black text-slate-950 text-sm">
                        <span className="text-[10px] opacity-30 mr-1">$</span>
                        {item.amount.toLocaleString('es-AR', { minimumFractionDigits: 2 })}
                      </td>
                      <td className="px-8 py-4 text-right">
                        <button
                          onClick={() => handleOpenDetail(item.id)}
                          className="p-2.5 bg-slate-50 text-slate-400 hover:bg-blue-600 hover:text-white rounded-xl transition-all shadow-sm active:scale-90"
                        >
                          <ChevronRight size={18} />
                        </button>
                      </td>
                    </motion.tr>
                  ))}
              </AnimatePresence>
            </tbody>
          </table>
        </div>
      </div>

      {/* PANEL LATERAL */}
      <AnimatePresence>
        {selectedItem && (
          <div className="fixed inset-0 bg-slate-950/40 backdrop-blur-sm z-[200] flex justify-end">
            <motion.div
              initial={{ x: '100%' }} animate={{ x: 0 }} exit={{ x: '100%' }}
              className="bg-white w-full max-w-xl h-full shadow-2xl flex flex-col border-l border-slate-200"
            >
              {/* HEADER DEL PANEL */}
              <div className="p-8 border-b border-slate-100 flex justify-between items-center bg-slate-50/30">
                <div>
                  <span className="text-[10px] font-black text-blue-600 uppercase tracking-[0.3em]">Auditoría de Aviso</span>
                  <h3 className="text-2xl font-black text-slate-900 tracking-tighter uppercase">#{selectedItem.listing.id.toString().padStart(6, '0')}</h3>
                </div>
                <button onClick={() => setSelectedItem(null)} className="p-3 hover:bg-slate-100 rounded-2xl transition-colors text-slate-400">
                  <X size={24} />
                </button>
              </div>

              {/* BARRA DE NAVEGACIÓN DE PESTAÑAS (TABS) */}
              <div className="flex bg-white border-b border-slate-100 px-8 gap-8">
                <button
                  onClick={() => setActiveDetailTab('info')}
                  className={clsx(
                    "py-4 text-[10px] font-black uppercase tracking-widest transition-all border-b-2",
                    activeDetailTab === 'info' ? "border-blue-600 text-blue-600" : "border-transparent text-slate-400 hover:text-slate-600"
                  )}
                >
                  Ficha Técnica
                </button>
                <button
                  onClick={() => setActiveDetailTab('claims')}
                  className={clsx(
                    "py-4 text-[10px] font-black uppercase tracking-widest transition-all border-b-2 flex items-center gap-2",
                    activeDetailTab === 'claims' ? "border-rose-500 text-rose-500" : "border-transparent text-slate-400 hover:text-slate-600"
                  )}
                >
                  Incidencias
                  {claims.length > 0 && (
                    <span className={clsx(
                      "px-1.5 py-0.5 rounded-md text-[9px]",
                      activeDetailTab === 'claims' ? "bg-rose-500 text-white" : "bg-slate-100 text-slate-400"
                    )}>
                      {claims.length}
                    </span>
                  )}
                </button>
              </div>

              {/* CUERPO DEL PANEL CON SCROLL INDEPENDIENTE */}
              <div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
                <AnimatePresence mode="wait">

                  {/* PESTAÑA 1: INFORMACIÓN GENERAL */}
                  {activeDetailTab === 'info' && (
                    <motion.div
                      key="info-tab" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}
                      className="space-y-10"
                    >
                      {/* Status & Total */}
                      <div className="bg-blue-600 text-white p-6 rounded-[2rem] shadow-xl shadow-blue-200 relative overflow-hidden">
                        <div className="absolute top-0 right-0 p-4 opacity-20"><CheckCircle2 size={80} /></div>
                        <div className="relative z-10">
                          <span className="text-[10px] font-black uppercase opacity-60">Recaudación Total</span>
                          <div className="text-4xl font-mono font-black">$ {selectedItem.listing.adFee?.toLocaleString('es-AR')}</div>
                          <div className="mt-4 flex items-center gap-2 text-[10px] font-bold uppercase bg-white/10 w-fit px-3 py-1 rounded-full border border-white/20">
                            <ShieldCheck size={14} /> {selectedItem.listing.status}
                          </div>
                        </div>
                      </div>

                      {/* Texto para Imprenta */}
                      <section>
                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
                          <FileText size={14} className="text-slate-500" /> Cuerpo de Publicación
                        </h4>
                        <div className="p-6 bg-slate-900 rounded-[1.5rem] text-slate-300 font-mono text-sm leading-relaxed uppercase">
                          {selectedItem.listing.description}
                        </div>
                      </section>

                      {/* Desglose de Pagos */}
                      <section>
                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
                          <Banknote size={14} className="text-emerald-500" /> Medios de Pago
                        </h4>
                        <div className="space-y-3">
                          {selectedItem.payments?.map((p: any, pIdx: number) => (
                            <div key={pIdx} className="bg-slate-50 p-4 rounded-2xl border border-slate-100 flex justify-between items-center">
                              <div className="flex items-center gap-4">
                                <div className="p-2 bg-white rounded-xl shadow-sm text-slate-400">
                                  {p.paymentMethod === 'Cash' ? <Banknote size={18} /> : <CreditCard size={18} />}
                                </div>
                                <span className="font-black text-slate-700 uppercase text-[11px]">{p.paymentMethod} {p.cardPlan || ''}</span>
                              </div>
                              <span className="font-mono font-black text-slate-900">$ {p.amount.toLocaleString()}</span>
                            </div>
                          ))}
                        </div>
                      </section>

                      {/* Datos Técnicos */}
                      <section className="grid grid-cols-2 gap-3">
                        <InfoBox label="Rubro" value={selectedItem.listing.categoryName} />
                        <InfoBox label="Duración" value={`${selectedItem.listing.printDaysCount} DÍAS`} />
                        <InfoBox label="Fecha Op." value={new Date(selectedItem.listing.createdAt).toLocaleDateString()} />
                        <InfoBox label="Responsable" value={selectedItem.listing.userId ? `ID #${selectedItem.listing.userId}` : 'Web'} />
                      </section>
                    </motion.div>
                  )}

                  {/* PESTAÑA 2: INCIDENCIAS Y RECLAMOS */}
                  {activeDetailTab === 'claims' && (
                    <motion.div
                      key="claims-tab" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}
                      className="space-y-6"
                    >
                      <div className="flex items-center justify-between">
                        <h4 className="text-[10px] font-black text-rose-500 uppercase tracking-widest flex items-center gap-2">
                          <ShieldAlert size={14} /> Historial de Reclamos
                        </h4>
                        <span className="text-[9px] font-bold text-slate-400 uppercase">Total: {claims.length} eventos</span>
                      </div>

                      {claims.length === 0 ? (
                        <div className="py-20 flex flex-col items-center justify-center bg-slate-50 rounded-[2rem] border-2 border-dashed border-slate-100 text-slate-300">
                          <ShieldAlert size={40} className="mb-4 opacity-20" />
                          <p className="font-black text-[10px] uppercase tracking-widest">Sin incidencias registradas</p>
                        </div>
                      ) : (
                        <div className="space-y-6">
                          {claims.map((c: any) => (
                            <div key={c.id} className={clsx(
                              "p-6 rounded-[2rem] border-2 transition-all relative",
                              c.status === 'Open' ? "bg-rose-50 border-rose-100 shadow-lg shadow-rose-100/50" : "bg-emerald-50 border-emerald-100"
                            )}>
                              {/* ... (Contenido del card de reclamo, igual que antes) ... */}
                              <div className="flex justify-between items-start mb-4">
                                <span className={clsx(
                                  "px-2.5 py-1 rounded-lg text-[9px] font-black uppercase tracking-tighter",
                                  c.status === 'Open' ? "bg-rose-500 text-white" : "bg-emerald-500 text-white"
                                )}>
                                  {c.status === 'Open' ? 'Pendiente de Resolución' : 'Incidencia Resuelta'}
                                </span>
                                <span className="text-[10px] font-bold text-slate-400">{new Date(c.createdAt).toLocaleDateString()}</span>
                              </div>
                              <p className="text-sm font-black text-slate-800 uppercase mb-2">{c.claimType}</p>
                              <p className="text-xs text-slate-600 leading-relaxed bg-white/50 p-3 rounded-xl border border-black/5 italic mb-4">"{c.description}"</p>

                              {c.status === 'Open' ? (
                                <button
                                  onClick={() => setResolvingClaim(c)}
                                  className="w-full py-3 bg-white border border-rose-200 text-rose-500 rounded-xl text-[10px] font-black uppercase hover:bg-rose-500 hover:text-white transition-all flex items-center justify-center gap-2"
                                >
                                  <CheckCircle2 size={14} /> Brindar Solución
                                </button>
                              ) : (
                                <div className="space-y-2 mt-4 pt-4 border-t border-black/5">
                                  {c.originalValues && (
                                    <div className="p-3 bg-slate-200/50 rounded-xl">
                                      <p className="text-[8px] font-black text-slate-400 uppercase mb-1">Snapshot Pre-ajuste:</p>
                                      <p className="text-[10px] text-slate-500 font-mono leading-tight">{c.originalValues}</p>
                                    </div>
                                  )}
                                  <div className="p-3 bg-white rounded-xl border border-emerald-200">
                                    <p className="text-[9px] font-black text-emerald-700 uppercase mb-1">Solución aplicada:</p>
                                    <p className="text-[11px] text-emerald-800 font-bold italic">"{c.solutionDescription}"</p>
                                    <p className="text-[8px] mt-2 text-emerald-600/50 font-black uppercase">Por: {c.resolvedByUsername} • {new Date(c.resolvedAt).toLocaleDateString()}</p>
                                  </div>
                                </div>
                              )}
                            </div>
                          ))}
                        </div>
                      )}
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>

              {/* FOOTER GLOBAL (SIEMPRE VISIBLE) */}
              <div className="p-8 bg-slate-50 border-t border-slate-100 flex gap-4">
                <button onClick={handlePrintDuplicate} className="flex-1 bg-white border-2 border-slate-200 text-slate-600 font-black text-[10px] uppercase py-4 rounded-2xl hover:bg-slate-100 transition-all flex items-center justify-center gap-2">
                  <Printer size={16} /> Duplicado Ticket
                </button>
                <button onClick={() => setShowClaimModal(true)} className="flex-1 bg-slate-900 text-white font-black text-[10px] uppercase py-4 rounded-2xl hover:bg-black transition-all flex items-center justify-center gap-2 shadow-lg">
                  <MessageSquare size={16} className="text-blue-400" /> Abrir Reclamo
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* MODAL DE RECLAMO */}
      <AnimatePresence>
        {showClaimModal && selectedItem && (
          <ClaimModal
            listingId={selectedItem.listing.id}
            onClose={() => setShowClaimModal(false)}
            onSuccess={() => loadItemClaims(selectedItem.listing.id)}
          />
        )}
      </AnimatePresence>
      {/* MODAL DE RESOLUCION DE RECLAMO */}
      <AnimatePresence>
        {resolvingClaim && selectedItem && (
          <ResolveClaimModal
            claim={resolvingClaim}
            listing={selectedItem.listing}
            onClose={() => setResolvingClaim(null)}
            onSuccess={() => {
              loadItemClaims(selectedItem.listing.id);
              loadHistory();
            }}
          />
        )}
      </AnimatePresence>
    </div>
  );
}

function InfoBox({ label, value, color = "text-slate-800" }: any) {
  return (
    <div className="p-3.5 bg-white border border-slate-100 rounded-xl shadow-sm">
      <span className="text-[8px] font-black text-slate-400 uppercase block mb-0.5 tracking-widest">{label}</span>
      <span className={clsx("text-[11px] font-black uppercase truncate block", color)}>{value}</span>
    </div>
  );
}