"use client";

import { useState, useEffect } from "react";

const STORAGE_KEY = "aw_compare_list";
const MAX_COMPARE = 3;

interface CompareItem {
  id: number;
  id_aw: string | null;
  username: string | null;
}

function getCompareList(): CompareItem[] {
  if (typeof window === "undefined") return [];
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  } catch {
    return [];
  }
}

function saveCompareList(list: CompareItem[]) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
  } catch {}
  // Dispatch a custom event so the floating bar updates
  window.dispatchEvent(new Event("compare-updated"));
}

export function CompareAddButton({ escort }: { escort: CompareItem }) {
  const [inList, setInList] = useState(false);

  useEffect(() => {
    const check = () => {
      const list = getCompareList();
      setInList(list.some((e) => e.id === escort.id));
    };
    check();
    window.addEventListener("compare-updated", check);
    return () => window.removeEventListener("compare-updated", check);
  }, [escort.id]);

  function toggle(e: React.MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    const list = getCompareList();
    if (inList) {
      saveCompareList(list.filter((e) => e.id !== escort.id));
    } else {
      if (list.length >= MAX_COMPARE) return; // max reached
      saveCompareList([...list, { id: escort.id, id_aw: escort.id_aw, username: escort.username }]);
    }
  }

  return (
    <button
      onClick={toggle}
      className={`flex h-10 w-10 items-center justify-center rounded-full backdrop-blur-sm transition-colors ${
        inList
          ? "bg-primary text-white"
          : "bg-black/40 text-white/80 hover:text-primary"
      }`}
      title={inList ? "Remove from comparison" : "Add to comparison"}
    >
      {inList ? (
        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
        </svg>
      ) : (
        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
        </svg>
      )}
    </button>
  );
}

export function CompareFloatingBar() {
  const [list, setList] = useState<CompareItem[]>([]);

  useEffect(() => {
    const update = () => setList(getCompareList());
    update();
    window.addEventListener("compare-updated", update);
    window.addEventListener("storage", update);
    return () => {
      window.removeEventListener("compare-updated", update);
      window.removeEventListener("storage", update);
    };
  }, []);

  function remove(id: number) {
    const newList = list.filter((e) => e.id !== id);
    saveCompareList(newList);
  }

  function clearAll() {
    saveCompareList([]);
  }

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

  return (
    <div
      className="fixed bottom-[calc(4.5rem+env(safe-area-inset-bottom))] md:bottom-4 left-1/2 -translate-x-1/2 z-[9997] bg-zinc-900 border border-zinc-700 rounded-xl shadow-2xl px-4 py-3 flex items-center gap-3 animate-in slide-in-from-bottom"
      // R17 A.3: on mobile, the bottom-nav (h-16) sits at bottom-0; the
      // compare bar used to overlap it. Push above the nav + safe-area
      // on small screens; revert to bottom-4 on md+.
    >
      <span className="text-sm font-medium text-white whitespace-nowrap">
        Compare ({list.length}/{MAX_COMPARE})
      </span>
      <div className="flex items-center gap-2">
        {list.map((item) => (
          <span
            key={item.id}
            className="inline-flex items-center gap-1 bg-surface-light text-text-muted text-xs px-2 py-1 rounded-full"
          >
            {item.username ?? "Escort"}
            <button
              onClick={() => remove(item.id)}
              aria-label={`Remove ${item.username ?? "escort"} from comparison`}
              className="text-text-muted hover:text-white p-2 -m-1"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </span>
        ))}
      </div>
      {list.length >= 2 && (
        <a
          href={`/compare?ids=${list.map((e) => e.id_aw ?? e.id).join(",")}`}
          className="bg-primary hover:bg-primary-dark text-white text-sm font-medium px-4 py-1.5 rounded-lg transition-colors whitespace-nowrap"
        >
          Compare Now
        </a>
      )}
      <button
        onClick={clearAll}
        className="text-text-muted hover:text-white text-xs underline whitespace-nowrap"
      >
        Clear
      </button>
    </div>
  );
}
