"use client";

import { useRouter } from "next/navigation";

export default function AddToCompare({ idAw }: { idAw: string }) {
  const router = useRouter();

  const handleAdd = () => {
    // Read current compare IDs from URL search params or build fresh
    const url = new URL(window.location.href);
    const currentCompareUrl = new URL("/compare", window.location.origin);

    // Check localStorage for current comparison IDs
    let ids: string[] = [];
    try {
      const stored = localStorage.getItem("compare_ids");
      if (stored) ids = JSON.parse(stored);
    } catch {
      // ignore
    }

    if (ids.includes(idAw)) {
      // Already in comparison
      router.push(`/compare?ids=${ids.join(",")}`);
      return;
    }

    if (ids.length >= 3) {
      // Remove oldest, add new
      ids = [...ids.slice(1), idAw];
    } else {
      ids.push(idAw);
    }

    try {
      localStorage.setItem("compare_ids", JSON.stringify(ids));
    } catch {
      // ignore
    }

    router.push(`/compare?ids=${ids.join(",")}`);
  };

  return (
    <button
      onClick={handleAdd}
      className="inline-flex items-center gap-2 border border-white/20 hover:border-gold/50 text-white hover:text-gold px-4 py-2 rounded-lg transition-all duration-200 text-sm font-medium"
      title="Add to comparison (max 3)"
    >
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
      </svg>
      Compare
    </button>
  );
}
