'use client';

import Link from 'next/link';
import React from 'react';

type Variant = 'primary' | 'ghost' | 'outline';

type CommonProps = {
  variant?: Variant;
  className?: string;
  children: React.ReactNode;
  iconRight?: React.ReactNode;
};

type AsButton = CommonProps & { href?: undefined } & React.ButtonHTMLAttributes<HTMLButtonElement>;
type AsLink = CommonProps & { href: string; target?: string; rel?: string };

export function PremiumButton(props: AsButton | AsLink) {
  const { variant = 'primary', className = '', children, iconRight, ...rest } = props as CommonProps & Record<string, unknown>;
  const cls = `btn btn-${variant} ${className}`.trim();

  const inner = (
    <>
      <span>{children}</span>
      {iconRight ?? (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <line x1="5" y1="12" x2="19" y2="12" />
          <polyline points="12 5 19 12 12 19" />
        </svg>
      )}
    </>
  );

  if ('href' in props && props.href) {
    const isExternal = /^https?:/.test(props.href);
    if (isExternal) {
      return (
        <a className={cls} href={props.href} target={(rest as { target?: string }).target ?? '_blank'} rel={(rest as { rel?: string }).rel ?? 'noopener noreferrer'}>
          {inner}
        </a>
      );
    }
    return (
      <Link className={cls} href={props.href}>
        {inner}
      </Link>
    );
  }

  return (
    <button className={cls} {...(rest as React.ButtonHTMLAttributes<HTMLButtonElement>)}>
      {inner}
    </button>
  );
}
