'use client'

import { useState, useEffect } from 'react'
import { MessageCircle, Phone, X } from 'lucide-react'

export function WhatsAppButton({ phone, message }: { phone?: string; message?: string }) {
  if (!phone) return null
  const url = `https://wa.me/${phone.replace(/\D/g, '')}${message ? `?text=${encodeURIComponent(message)}` : ''}`
  return (
    <a
      href={url}
      target="_blank"
      rel="noopener noreferrer"
      className="flex items-center justify-center w-10 h-10 rounded-full bg-green-500 text-white hover:bg-green-600 transition-colors shrink-0"
      title="واتساب"
    >
      <MessageCircle className="w-5 h-5" />
    </a>
  )
}

export function FloatingActionButtons() {
  const [whatsapp, setWhatsapp] = useState('')
  const [phone, setPhone] = useState('')
  const [expanded, setExpanded] = useState(false)

  useEffect(() => {
    fetch('/api/settings')
      .then(r => r.json())
      .then(d => {
        const brand = d.brand || {}
        setWhatsapp(brand.whatsapp || '')
        setPhone(brand.phone || '')
      })
      .catch(() => {})
  }, [])

  if (!whatsapp && !phone) return null

  return (
    <div className="fixed bottom-6 left-6 z-50 flex flex-col items-center gap-3" dir="ltr">
      {expanded && (
        <div className="flex flex-col gap-3 animate-[slide-up_0.2s_ease-out]">
          {whatsapp && (
            <a
              href={`https://wa.me/${whatsapp.replace(/\D/g, '')}`}
              target="_blank"
              rel="noopener noreferrer"
              className="w-12 h-12 rounded-full bg-green-500 text-white flex items-center justify-center shadow-lg hover:bg-green-600 hover:scale-110 transition-all"
              title="واتساب"
            >
              <MessageCircle className="w-6 h-6" />
            </a>
          )}
          {phone && (
            <a
              href={`tel:${phone}`}
              className="w-12 h-12 rounded-full bg-blue-600 text-white flex items-center justify-center shadow-lg hover:bg-blue-700 hover:scale-110 transition-all"
              title="اتصال"
            >
              <Phone className="w-6 h-6" />
            </a>
          )}
        </div>
      )}
      <button
        onClick={() => setExpanded(!expanded)}
        className={`w-14 h-14 rounded-full shadow-xl flex items-center justify-center text-white transition-all duration-200 ${expanded ? 'bg-red-500 rotate-45' : 'bg-blue-600'}`}
        title={expanded ? 'إغلاق' : 'تواصل معنا'}
      >
        {expanded ? <X className="w-7 h-7" /> : <MessageCircle className="w-7 h-7" />}
      </button>
    </div>
  )
}
