'use client';
import { useEffect, useState } from 'react';

export function CartButton() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const stored = JSON.parse(localStorage.getItem('mdv_cart') ?? '{"items":[]}') as { items?: unknown[] };
    setCount((stored.items ?? []).length);
    const onUpdate = () => {
      const s = JSON.parse(localStorage.getItem('mdv_cart') ?? '{"items":[]}') as { items?: unknown[] };
      setCount((s.items ?? []).length);
    };
    window.addEventListener('mdv:cart-updated', onUpdate);
    return () => window.removeEventListener('mdv:cart-updated', onUpdate);
  }, []);
  return (
    <a
      href="/carrito"
      className="relative inline-flex items-center text-sm font-medium text-stone-700 hover:text-emerald-800"
      aria-label="Ver carrito"
    >
      <span aria-hidden="true">🛒</span>
      {count > 0 && (
        <span className="ml-1 inline-flex h-5 min-w-5 items-center justify-center rounded-full bg-emerald-700 px-1 text-xs font-semibold text-white">
          {count}
        </span>
      )}
    </a>
  );
}