'use client'

import { useSyncExternalStore } from 'react'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { Link2, Share2 } from 'lucide-react'
import { FaFacebookF, FaLinkedinIn, FaWhatsapp } from 'react-icons/fa'
import { FaXTwitter } from 'react-icons/fa6'

interface BlogShareBarProps {
  title: string
}

const NETWORKS = [
  { name: 'Facebook', Icon: FaFacebookF, build: (u: string) => `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(u)}` },
  { name: 'X', Icon: FaXTwitter, build: (u: string, title: string) => `https://twitter.com/intent/tweet?url=${encodeURIComponent(u)}&text=${encodeURIComponent(title)}` },
  { name: 'LinkedIn', Icon: FaLinkedinIn, build: (u: string) => `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(u)}` },
  { name: 'WhatsApp', Icon: FaWhatsapp, build: (u: string, title: string) => `https://wa.me/?text=${encodeURIComponent(`${title} ${u}`)}` },
]

const noopSubscribe = () => () => {}

// Share targets are plain intent URLs (no third-party SDKs/scripts), built
// from the real, locale-prefixed page URL at click time.
export default function BlogShareBar({ title }: BlogShareBarProps) {
  const t = useTranslations('Blog')
  const tp = useTranslations('BlogPage')
  const canNativeShare = useSyncExternalStore(
    noopSubscribe,
    () => typeof navigator.share === 'function',
    () => false,
  )

  const openShare = (build: (u: string, title: string) => string) => {
    window.open(build(window.location.href, title), '_blank', 'noopener,noreferrer,width=640,height=560')
  }

  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(window.location.href)
      toast.success(t('linkCopied'))
    } catch {
      toast.error(t('shareFailed'))
    }
  }

  const nativeShare = async () => {
    try {
      await navigator.share({ title, url: window.location.href })
    } catch {
      // user dismissed the share sheet — not an error
    }
  }

  const buttonClass = 'w-10 h-10 rounded-full flex items-center justify-center bg-gray-100 text-dark hover:bg-primary hover:text-white transition cursor-pointer'

  return (
    <div className="flex flex-wrap items-center justify-between gap-4 rounded-2xl border border-gray-100 bg-white px-5 py-4">
      <p className="font-semibold text-dark">{tp('shareArticle')}</p>
      <div className="flex flex-wrap items-center gap-2">
        {NETWORKS.map(({ name, Icon, build }) => (
          <button
            key={name}
            type="button"
            onClick={() => openShare(build)}
            aria-label={tp('shareOn', { network: name })}
            title={name}
            className={buttonClass}
          >
            <Icon size={15} />
          </button>
        ))}
        <button type="button" onClick={copyLink} aria-label={tp('copyLink')} title={tp('copyLink')} className={buttonClass}>
          <Link2 size={16} />
        </button>
        {canNativeShare && (
          <button type="button" onClick={nativeShare} aria-label={t('share')} title={t('share')} className={`${buttonClass} sm:hidden`}>
            <Share2 size={16} />
          </button>
        )}
      </div>
    </div>
  )
}
