'use client';

import { useEffect, useRef, useState, type MouseEvent } from 'react';

/** Clicking copies the address; falls back to the mailto link when the clipboard is unavailable. */
export default function ProfileEmail({ email }: { email: string }) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);

  useEffect(() => () => clearTimeout(timer.current), []);

  const onClick = (e: MouseEvent<HTMLAnchorElement>) => {
    if (!navigator.clipboard) return;
    e.preventDefault();
    navigator.clipboard
      .writeText(email)
      .then(() => {
        setCopied(true);
        clearTimeout(timer.current);
        timer.current = setTimeout(() => setCopied(false), 1800);
      })
      .catch(() => {
        window.location.href = `mailto:${email}`;
      });
  };

  return (
    <a className="profile-email text-xxl fw-400 color-white" id="profileEmail" href={`mailto:${email}`} onClick={onClick}>
      {copied ? 'Copied to clipboard' : email}
    </a>
  );
}
