← back to Watches

src/components/ShareButton.jsx

67 lines

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { shareWatch } from '../utils/pwaUtils';

/**
 * Share Button Component
 * Uses native Web Share API for mobile sharing
 */
function ShareButton({ watch, className = '' }) {
  const [showCopied, setShowCopied] = useState(false);

  const handleShare = async () => {
    // Try native share first
    const shared = await shareWatch(watch);

    // Fallback to clipboard copy if Web Share API not available
    if (!shared) {
      const url = `${window.location.origin}?watch=${watch.id}`;

      try {
        await navigator.clipboard.writeText(url);
        setShowCopied(true);
        setTimeout(() => setShowCopied(false), 2000);
      } catch (error) {
        console.error('Failed to copy to clipboard:', error);
      }
    }
  };

  return (
    <div className="relative">
      <button
        onClick={handleShare}
        className={`flex items-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-800 dark:text-white rounded-lg transition-colors ${className}`}
      >
        <svg
          className="w-5 h-5"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"
          />
        </svg>
        <span>Share</span>
      </button>

      {showCopied && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0 }}
          className="absolute top-full left-1/2 transform -translate-x-1/2 mt-2 bg-green-500 text-white text-sm px-3 py-1 rounded-lg whitespace-nowrap z-10"
        >
          Link copied to clipboard!
        </motion.div>
      )}
    </div>
  );
}

export default ShareButton;