import { Share2, Check } from "lucide-react";
import { useState } from "react";

export function ShareButton({
  reference,
  text,
}: {
  reference: string;
  text: string;
}) {
  const [copied, setCopied] = useState(false);
  const message = `Today's Bible Word: ${reference}\n\n${text.slice(0, 180)}${text.length > 180 ? "…" : ""}\n\nRead more at BibleWordOfTheDay.com`;

  async function handle() {
    try {
      if (typeof navigator !== "undefined" && "share" in navigator) {
        await (navigator as Navigator).share({
          title: `Bible Word — ${reference}`,
          text: message,
        });
        return;
      }
    } catch {
      /* user cancelled — fall through to copy */
    }
    try {
      await navigator.clipboard.writeText(message);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch {
      /* noop */
    }
  }

  return (
    <button
      onClick={handle}
      className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-2 text-sm font-medium text-primary shadow-soft transition hover:border-[var(--gold)] hover:text-[var(--gold)]"
    >
      {copied ? <Check className="h-4 w-4" /> : <Share2 className="h-4 w-4" />}
      {copied ? "Copied" : "Share"}
    </button>
  );
}
