"use client";

import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { useEffect, useState } from "react";

export default function BackToResults() {
  const searchParams = useSearchParams();
  const [backUrl, setBackUrl] = useState<string | null>(null);

  useEffect(() => {
    // Check query param first, then referrer
    const fromParam = searchParams.get("from");
    if (fromParam) {
      setBackUrl(fromParam);
      return;
    }

    if (typeof document !== "undefined" && document.referrer) {
      const ref = new URL(document.referrer);
      const currentHost = window.location.host;
      if (ref.host === currentHost) {
        const path = ref.pathname;
        if (
          path.includes("/search") ||
          path.includes("/escorts") ||
          path === "/"
        ) {
          setBackUrl(ref.pathname + ref.search);
        }
      }
    }
  }, [searchParams]);

  if (!backUrl) return null;

  return (
    <Link
      href={backUrl}
      className="inline-flex items-center gap-1.5 text-sm text-text-muted hover:text-white transition-colors mb-4"
    >
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
      </svg>
      Back to search results
    </Link>
  );
}
