'use client';
import { useRef } from 'react';

interface SecureEmailProps {
  /**
   * base64-encoded email, e.g. btoa('pastoor')
   */
  user: string;

  /**
   * base64-encoded domain, e.g. btoa('parochie.nl')
   */
  domain: string;
  label?: string;
}

/**
 * Generates a secure email link that requires user interaction to reveal the actual "mailto:" address,
 * preventing the address from being easily scraped by bots.
 *
 * @param {Object} props - The properties for the SecureEmail component.
 * @param {string} props.user - The Base64-encoded user portion of the email address.
 * @param {string} props.domain - The Base64-encoded domain portion of the email address.
 * @param {string} [props.label='E-Mail schreiben'] - The label text displayed for the email link.
 * @return {JSX.Element} A React component that renders an email link.
 */
export function SecureEmail({ user, domain, label = 'E-Mail schreiben' }: SecureEmailProps) {
  const ref = useRef<HTMLAnchorElement>(null);

  // Decode and write the real mailto: into the href, imperatively (not via state),
  // so it's in place synchronously before the browser navigates.
  const reveal = () => {
    const el = ref.current;
    if (!el || el.href.startsWith('mailto:')) return;
    el.href = `mailto:${atob(user)}@${atob(domain)}`;
  };

  // Fallback: if a click somehow lands before reveal fired (some touch flows),
  // assemble the address then and navigate manually.
  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    if (!ref.current?.href.startsWith('mailto:')) {
      e.preventDefault();
      reveal();
      window.location.href = ref.current!.href;
    }
  };

  return (
  <a
    ref={ref}
    href="#"
    onMouseEnter={reveal}
    onFocus={reveal}
    onTouchStart={reveal}
    onClick={handleClick}>
      {label}
  </a>
);
}