"use client";

import { useState } from "react";

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

  const url = typeof window !== "undefined" ? window.location.href : "";
  const enc = encodeURIComponent(url);
  const encTitle = encodeURIComponent(title);

  const links = [
    {
      name: "Facebook",
      href: `https://www.facebook.com/sharer/sharer.php?u=${enc}`,
      color: "hover:bg-blue-50 hover:text-blue-600",
      icon: "f",
      label: "f",
    },
    {
      name: "X",
      href: `https://twitter.com/intent/tweet?url=${enc}&text=${encTitle}`,
      color: "hover:bg-slate-100 hover:text-slate-900",
      label: "𝕏",
    },
    {
      name: "LinkedIn",
      href: `https://www.linkedin.com/sharing/share-offsite/?url=${enc}`,
      color: "hover:bg-sky-50 hover:text-sky-700",
      label: "in",
    },
    {
      name: "WhatsApp",
      href: `https://wa.me/?text=${encTitle}%20${enc}`,
      color: "hover:bg-green-50 hover:text-green-600",
      label: "✆",
    },
  ];

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      /* ignore */
    }
  };

  return (
    <div className="flex flex-wrap items-center gap-2">
      <span className="mr-1 text-sm font-medium text-slate-500">Share:</span>
      {links.map((l) => (
        <a
          key={l.name}
          href={l.href}
          target="_blank"
          rel="noopener noreferrer"
          aria-label={`Share on ${l.name}`}
          className={`flex h-9 w-9 items-center justify-center rounded-lg border border-slate-200 text-sm font-bold text-slate-600 transition ${l.color}`}
        >
          {l.label}
        </a>
      ))}
      <button
        onClick={copy}
        className="flex h-9 items-center justify-center rounded-lg border border-slate-200 px-3 text-sm font-medium text-slate-600 transition hover:bg-slate-100"
      >
        {copied ? "Copied ✓" : "Copy Link"}
      </button>
    </div>
  );
}
