"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "react-hot-toast";
import React from "react";

interface SmartLinkProps {
  href: string;
  children: React.ReactNode;
  className?: string;
  [key: string]: unknown;
}

/**
 * SmartLink
 * A Next.js Link wrapper that:
 * - Checks if target URL is reachable before navigation.
 * - Shows toast errors instead of Chrome's default 503 page.
 * - Keeps client-side navigation (no full reload).
 */
export default function SmartLink({ href, children, className ,...props}: SmartLinkProps) {
  const router = useRouter();

  const handleClick = async (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();

    try {
      // Lightweight health check before navigation
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), 5000);

      const res = await fetch(href, {
        method: "HEAD",
        signal: controller.signal,
        cache: "no-store",
      });

      clearTimeout(timeout);

      if (!res.ok) {
        toast.error(`خطا سرویس: ${res.status}`);
        return;
      }

      router.push(href); // client-side route change
    } catch {
      toast.error("عدم دسترسی به سرویس. لطفاً بعداً دوباره تلاش کنید.");
    }
  };

  return (
    <Link href={href} onClick={handleClick} className={className} {...props}>
      {children}
    </Link>
  );
}
