import Link from "next/link";
import type { ReactNode } from "react";

type Variant = "primary" | "outline" | "quiet";

type Props = {
  href: string;
  children: ReactNode;
  variant?: Variant;
  /** Stretch to full width on mobile — avoids cramped side-by-side buttons. */
  block?: boolean;
  className?: string;
};

/**
 * `active:scale` is on the base so every variant answers a click, including
 * the text-only one. The lift is small on purpose: a button that jumps reads
 * as a card, and these sit in rows of two.
 */
const base =
  "group relative inline-flex items-center justify-center gap-2 font-display tracking-widest text-sm transition duration-200 ease-out active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent";

const variants: Record<Variant, string> = {
  primary:
    "sheen overflow-hidden px-8 py-3 bg-accent text-background hover:bg-foreground hover:-translate-y-0.5 hover:shadow-[0_14px_30px_-14px_rgba(196,184,150,0.6)]",
  outline:
    "px-8 py-3 border border-border text-foreground hover:border-accent hover:text-accent hover:-translate-y-0.5 hover:bg-accent/[0.06]",
  quiet: "underline-grow text-accent hover:text-foreground",
};

/**
 * Every call-to-action on the site. Automatically renders an `<a>` with the
 * right rel attributes for external URLs, and a Next `<Link>` otherwise.
 */
export function ButtonLink({
  href,
  children,
  variant = "primary",
  block = false,
  className = "",
}: Props) {
  const classes = `${base} ${variants[variant]} ${
    block ? "w-full sm:w-auto" : ""
  } ${className}`;

  const isExternal = /^https?:\/\//.test(href) || href.startsWith("mailto:");

  if (isExternal) {
    return (
      <a
        href={href}
        target={href.startsWith("mailto:") ? undefined : "_blank"}
        rel="noopener noreferrer"
        className={classes}
      >
        {children}
      </a>
    );
  }

  return (
    <Link href={href} className={classes}>
      {children}
    </Link>
  );
}
