import { useState, useEffect } from 'react';

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

const STORAGE_KEY = 'sp_compare';
const MAX_ITEMS = 3;

/** Add/remove item from compare. Returns updated list. */
export function toggleCompare(item: CompareItem): CompareItem[] {
  const stored = getCompareItems();
  const exists = stored.findIndex(i => i.id === item.id);
  let updated: CompareItem[];

  if (exists >= 0) {
    updated = stored.filter(i => i.id !== item.id);
  } else {
    if (stored.length >= MAX_ITEMS) {
      if ((window as any).__showToast) (window as any).__showToast(`Max ${MAX_ITEMS} sneakers vergelijken`, 'info');
      return stored;
    }
    updated = [...stored, item];
  }

  localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  window.dispatchEvent(new Event('sp-compare-update'));
  return updated;
}

export function getCompareItems(): CompareItem[] {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
  } catch {
    return [];
  }
}

export function clearCompare() {
  localStorage.removeItem(STORAGE_KEY);
  window.dispatchEvent(new Event('sp-compare-update'));
}

export default function CompareBar() {
  const [items, setItems] = useState<CompareItem[]>([]);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    setItems(getCompareItems());
    const handler = () => setItems(getCompareItems());
    window.addEventListener('sp-compare-update', handler);
    return () => window.removeEventListener('sp-compare-update', handler);
  }, []);

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

  return (
    <div className="fixed bottom-0 left-0 right-0 z-50 animate-slide-up">
      {/* Expanded comparison overlay */}
      {expanded && (
        <div className="fixed inset-0 z-50 bg-black/90 flex items-end sm:items-center justify-center p-4" onClick={() => setExpanded(false)}>
          <div className="w-full max-w-4xl rounded-t-3xl sm:rounded-3xl border border-[var(--border)]/50 bg-[var(--bg-card)] p-6 pb-[env(safe-area-inset-bottom)] max-h-[80vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-black text-[var(--text)]">Vergelijken</h2>
              <button onClick={() => setExpanded(false)} className="text-[var(--text-muted)] hover:text-[var(--text)]">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
              </button>
            </div>

            <div className={`grid gap-4 ${items.length === 2 ? 'grid-cols-2' : items.length === 3 ? 'grid-cols-3' : 'grid-cols-1'}`}>
              {items.map(item => (
                <div key={item.id} className="rounded-2xl border border-[var(--border)]/50 bg-[var(--bg-elevated)] p-4 text-center">
                  <img src={`/api/img/${item.id}`} alt={`${item.brand} ${item.name}`}
                       className="mx-auto h-32 w-32 object-contain mb-4" />
                  <p className="text-[10px] font-bold uppercase tracking-widest text-[var(--text-muted)]">{item.brand}</p>
                  <p className="font-semibold text-sm text-[var(--text)] mt-1">{item.name}</p>
                  <p className="text-lg font-black text-[var(--accent)] mt-2">€{item.price.toFixed(2).replace('.', ',')}</p>
                  <p className="text-xs text-[var(--text-muted)] mt-1">{item.shops} shops</p>
                  <a href={`/sneakers/${item.slug}`}
                     className="mt-3 inline-block rounded-lg bg-[var(--accent)] px-4 py-2 text-xs font-bold text-[var(--bg)]">
                    Bekijk
                  </a>
                </div>
              ))}
            </div>

            <div className="mt-4 text-center">
              <button onClick={() => { clearCompare(); setExpanded(false); }}
                      className="text-xs text-[var(--text-muted)] hover:text-[var(--text)]">
                Vergelijking wissen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Sticky bottom bar */}
      <div className="border-t border-[var(--border)]/50 bg-[var(--bg-card)]/95 backdrop-blur-sm px-4 py-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))]">
        <div className="mx-auto max-w-7xl flex items-center justify-between">
          <div className="flex items-center gap-3">
            <span className="text-sm font-semibold text-[var(--text)]">{items.length}/{MAX_ITEMS} geselecteerd</span>
            <div className="flex -space-x-2">
              {items.map(item => (
                <div key={item.id} className="relative h-10 w-10 rounded-full border-2 border-[var(--bg-card)] bg-[var(--bg-elevated)] overflow-hidden">
                  <img src={`/api/img/${item.id}`} alt="" className="h-full w-full object-contain" />
                </div>
              ))}
            </div>
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => { clearCompare(); }}
              className="rounded-lg px-3 py-2 text-xs text-[var(--text-muted)] hover:text-[var(--text)]"
            >
              Wissen
            </button>
            <button
              onClick={() => setExpanded(true)}
              disabled={items.length < 2}
              className="rounded-xl bg-[var(--accent)] px-5 py-2 text-sm font-bold text-[var(--bg)] transition-all hover:shadow-lg disabled:opacity-50"
            >
              Vergelijken
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
