import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { CompareBar, type CompareBarPackage } from '../../../components/molecules/CompareBar';
import { useComparisonBasket } from '../../shared/state/useComparisonBasket';
import { resolveComparisonPackage, parseBasketKey } from '../../shared/fixtures/packages';

const ERROR_TIMEOUT_MS = 2500;

/**
 * App-level CompareBar — hovers above every route except `/comparison`
 * itself. Reads the basket store, resolves keys to display labels, and
 * navigates to the comparison page when the user activates it.
 *
 * Surfaces transient error feedback (already-added / max-reached) by
 * forwarding `lastError` to CompareBar and auto-clearing after a moment.
 */
export function AppCompareBar() {
  const navigate = useNavigate();
  const location = useLocation();
  const packageKeys = useComparisonBasket((s) => s.packageKeys);
  const lastError = useComparisonBasket((s) => s.lastError);
  const clearError = useComparisonBasket((s) => s.clearError);

  useEffect(() => {
    if (!lastError) return;
    const t = setTimeout(clearError, ERROR_TIMEOUT_MS);
    return () => clearTimeout(t);
  }, [lastError, clearError]);

  if (location.pathname.startsWith('/comparison')) return null;

  const packages: CompareBarPackage[] = packageKeys
    .map((key) => {
      const pkg = resolveComparisonPackage(key);
      const parsed = parseBasketKey(key);
      if (!pkg || !parsed) return null;
      return {
        id: key,
        name: pkg.name,
        providerName: pkg.provider.name,
      };
    })
    .filter((p): p is CompareBarPackage => p !== null);

  // CompareBar slides in only when packages.length > 0. To surface "already
  // added" / "max reached" errors when the bar isn't yet visible (no items),
  // we'd need a separate toast. For now: errors only appear once the bar is
  // visible — fine for the common dupe case (basket has ≥1).
  return (
    <CompareBar
      packages={packages}
      onCompare={() => navigate('/comparison')}
      error={lastError ?? undefined}
    />
  );
}
