"use client"

import { Share2, Check } from "lucide-react"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { useToast } from "@/hooks/use-toast"

type Props = { url: string; title?: string; size?: "sm" | "default" }

export function ShareButton({ url, title, size = "default" }: Props) {
  const { toast } = useToast()
  const [copied, setCopied] = useState(false)

  const handleShare = async () => {
    try {
      if (navigator.share) {
        await navigator.share({ url, title })
        return
      }
    } catch {}
    try {
      await navigator.clipboard.writeText(url)
      setCopied(true)
      setTimeout(() => setCopied(false), 1000)
      toast({ title: "Link copied" })
    } catch (e) {
      window.location.href = `mailto:?subject=${encodeURIComponent(title || 'Check this facility')}&body=${encodeURIComponent(url)}`
    }
  }

  return (
    <Button onClick={handleShare} size={size} variant="outline">
      {copied ? <Check className="h-4 w-4" /> : <Share2 className="h-4 w-4" />}
    </Button>
  )
}


