import { useState, useEffect } from 'react';

interface RecentItem {
  id: string;
  slug: string;
  name: string;
  brand: string;
  price: number;
  image: string;
}

const STORAGE_KEY = 'sp_recently_viewed';
const MAX_ITEMS = 8;

/** Call this on product pages to track viewed items */
export function trackView(item: RecentItem) {
  try {
    const stored = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]') as RecentItem[];
    const filtered = stored.filter(i => i.id !== item.id);
    filtered.unshift(item);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered.slice(0, MAX_ITEMS)));
  } catch {}
}

export default function RecentlyViewed() {
  const [items, setItems] = useState<RecentItem[]>([]);

  useEffect(() => {
    try {
      const stored = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]') as RecentItem[];
      if (stored.length > 0) setItems(stored);
    } catch {}
  }, []);

  if (items.length === 0) return null;

  return (
    <section className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
      <h2 className="mb-6 text-sm font-bold uppercase tracking-widest text-[var(--text-muted)]">Recent bekeken</h2>
      <div className="flex gap-4 overflow-x-auto pb-2 scrollbar-hide">
        {items.map(item => (
          <a
            key={item.id}
            href={`/sneakers/${item.slug}`}
            className="group flex-shrink-0 w-36 sm:w-44"
          >
            <div className="aspect-square overflow-hidden rounded-xl bg-[var(--bg-elevated)] border border-[var(--border)]/50 transition-all group-hover:border-[var(--accent)]/30 group-hover:shadow-md">
              <img
                src={`/api/img/${item.id}`}
                alt={`${item.brand} ${item.name}`}
                width={176}
                height={176}
                className="h-full w-full object-contain transition-transform duration-300 group-hover:scale-110"
                loading="lazy"
                decoding="async"
                onError={(e) => { (e.target as HTMLImageElement).src = '/img/sneaker-placeholder.svg'; }}
              />
            </div>
            <div className="mt-2 px-0.5">
              <p className="text-[10px] font-bold uppercase tracking-widest text-[var(--text-muted)]">{item.brand}</p>
              <p className="text-xs font-semibold text-[var(--text)] leading-tight truncate">{item.name}</p>
              <p className="text-xs font-black text-[var(--accent)]">€{item.price.toFixed(2).replace('.', ',')}</p>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}
