"use client";

import { Share2, Check } from "lucide-react";
import { useState } from "react";

export function ShareButton({ url, title, text, className = "" }) {
  const [copied, setCopied] = useState(false);

  const copyToClipboardFallback = (text) => {
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    textArea.style.left = "-9999px";
    textArea.style.top = "-9999px";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
      document.execCommand("copy");
      return true;
    } catch (err) {
      return false;
    } finally {
      document.body.removeChild(textArea);
    }
  };

  const handleShare = async () => {
    const shareUrl =
      url || (typeof window !== "undefined" ? window.location.href : "");

    if (!shareUrl) return;

    const shareData = {
      title: title || "Trains of Rajbari",
      text: text || "Check out the train schedules for Rajbari district",
      url: shareUrl,
    };

    // Check if Web Share API is available (mobile devices)
    if (typeof navigator !== "undefined" && navigator.share) {
      try {
        await navigator.share(shareData);
        return;
      } catch (err) {
        // User cancelled sharing - don't fallback to copy
        if (err.name === "AbortError") return;
        // For other errors, fall through to clipboard copy
      }
    }

    // Fallback: Copy to clipboard
    if (typeof navigator !== "undefined" && navigator.clipboard) {
      try {
        await navigator.clipboard.writeText(shareUrl);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
        return;
      } catch (err) {
        // clipboard API failed, try execCommand fallback
      }
    }

    // Final fallback: execCommand
    if (copyToClipboardFallback(shareUrl)) {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  return (
    <button
      onClick={handleShare}
      className={`inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm hover:shadow-md ${className}`}
      aria-label="Share this page"
    >
      {copied ? (
        <>
          <Check className="w-4 h-4" />
          <span>Link Copied!</span>
        </>
      ) : (
        <>
          <Share2 className="w-4 h-4" />
          <span>Share</span>
        </>
      )}
    </button>
  );
}
