"use client";

import { useState } from "react";
import { Facebook, MessageCircle, Send, Link2, Check } from "lucide-react";

// Custom X (Twitter) glyph — lucide-react's Twitter icon is the legacy bird.
function XIcon({ size = 16 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
    </svg>
  );
}

export function ShareButtons({ url, title }: { url: string; title: string }) {
  const [copied, setCopied] = useState(false);

  const encodedUrl = encodeURIComponent(url);
  const encodedTitle = encodeURIComponent(title);

  const links = [
    {
      label: "فيسبوك",
      href: `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`,
      icon: <Facebook size={16} />,
    },
    {
      label: "إكس",
      href: `https://twitter.com/intent/tweet?url=${encodedUrl}&text=${encodedTitle}`,
      icon: <XIcon />,
    },
    {
      label: "واتساب",
      href: `https://wa.me/?text=${encodedTitle}%20${encodedUrl}`,
      icon: <MessageCircle size={16} />,
    },
    {
      label: "تيليجرام",
      href: `https://t.me/share/url?url=${encodedUrl}&text=${encodedTitle}`,
      icon: <Send size={16} />,
    },
  ];

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Clipboard API unavailable — silently ignore; the copy button
      // simply won't confirm success.
    }
  };

  return (
    <div className="flex flex-wrap items-center gap-2">
      <span className="text-xs text-ink-400">شارك:</span>
      {links.map((l) => (
        <a
          key={l.label}
          href={l.href}
          target="_blank"
          rel="noopener noreferrer"
          aria-label={`مشاركة عبر ${l.label}`}
          className="flex h-8 w-8 items-center justify-center rounded-full border border-ink-100 text-ink-600 hover:border-brand hover:text-brand dark:border-ink-800 dark:text-ink-200"
        >
          {l.icon}
        </a>
      ))}
      <button
        type="button"
        onClick={handleCopy}
        aria-label="نسخ الرابط"
        className="flex h-8 w-8 items-center justify-center rounded-full border border-ink-100 text-ink-600 hover:border-brand hover:text-brand dark:border-ink-800 dark:text-ink-200"
      >
        {copied ? <Check size={16} /> : <Link2 size={16} />}
      </button>
    </div>
  );
}
