"use client";

import { useState, useEffect } from "react";

function readCartCount(): number {
  try {
    const raw = localStorage.getItem("kc_cart");
    if (!raw) return 0;
    const items = JSON.parse(raw);
    return Array.isArray(items)
      ? items.reduce((s: number, i: { quantity?: number }) => s + (i.quantity || 0), 0)
      : 0;
  } catch {
    return 0;
  }
}

export default function CartCount() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(readCartCount());

    const refresh = () => setCount(readCartCount());

    // same-tab cart updates
    window.addEventListener("cart-updated", refresh);
    // cross-tab updates
    window.addEventListener("storage", (e) => {
      if (e.key === "kc_cart" || e.key === null) refresh();
    });

    return () => {
      window.removeEventListener("cart-updated", refresh);
    };
  }, []);

  if (count === 0) return null;

  return (
    <span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 bg-gold-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center">
      {count > 99 ? "99+" : count}
    </span>
  );
}
