'use client';

import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowLeft } from 'lucide-react';

type BackButtonProps = {
  className?: string;
  ariaLabel?: string;
  hrefFallback?: string; // default '/'
  children?: React.ReactNode; // custom icon/content; defaults to ArrowLeft
};

/**
 * BackButton
 * - Primary: attempts to close the current window/tab (window.close())
 * - Fallback: if close fails (e.g., not opened by script), navigates to '/'
 * - Uses <Link> so that Ctrl/Cmd-click or middle-click opens the fallback URL in a new tab naturally
 */
export default function BackButton({ className, ariaLabel = '返回', hrefFallback = '/', children }: BackButtonProps) {
  const router = useRouter();

  const onClick = React.useCallback<React.MouseEventHandler<HTMLAnchorElement>>((e) => {
    // Respect modifier clicks (new tab/window) and non-left clicks
    if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;

    e.preventDefault();
    
    // Try to close the window first
    if (typeof window !== 'undefined') {
      window.close();
      
      // If window.close() didn't work (window still open after a short delay),
      // navigate to the fallback URL
      setTimeout(() => {
        if (!document.hidden) {
          router.push(hrefFallback);
        }
      }, 80);
    }
  }, [router, hrefFallback]);

  return (
    <Link
      href={hrefFallback}
      aria-label={ariaLabel}
      onClick={onClick}
      className={className}
    >
      {children ?? <ArrowLeft size={18} />}
    </Link>
  );
}
