'use client'

import { useRef, useEffect, useState, useCallback } from 'react'
import Image from 'next/image'
import { Phone, Mail, MapPin, Share2, Download, Facebook, Instagram, Youtube } from 'lucide-react'
import { imageUrls } from '@/lib/images'
import { useLanguage } from '@/lib/LanguageContext'
import { getTranslation } from '@/lib/i18n'

const VCARD_DATA = {
  name: 'Kevin Victor',
  job: 'Real Estate Professional',
  company: 'Hogar Realtors',
  mobile: '+52 322 231 1415',
  telRaw: '+523222311415',
  email: 'kevin@hogarrealtors.com',
  website: 'https://www.kevinvictorrealestate.com',
  address: 'Aquiles Serdán 382, Puerto Vallarta, Jal., Mexico 48380',
  addressStreet: 'Aquiles Serdán 382',
  city: 'Puerto Vallarta',
  region: 'Jalisco',
  postalCode: '48380',
  country: 'Mexico',
  facebook: 'https://www.facebook.com/kevinvictor.realestate',
  instagram: 'https://www.instagram.com/kevinvictor.realestate/',
  youtube: 'https://www.youtube.com/@KEVINVICTOR.REALESTATE',
}

function generateVcf(): string {
  const v = VCARD_DATA
  return [
    'BEGIN:VCARD',
    'VERSION:3.0',
    `N:Victor;Kevin;;;`,
    `FN:${v.name}`,
    `ORG:${v.company}`,
    `TITLE:${v.job}`,
    `TEL;TYPE=CELL:${v.telRaw.replace(/\s/g, '')}`,
    `EMAIL:${v.email}`,
    `URL:${v.website}`,
    `ADR;TYPE=WORK:;;${v.addressStreet};${v.city};${v.region};${v.postalCode};${v.country}`,
    `URL:${v.facebook}`,
    `URL:${v.instagram}`,
    `URL:${v.youtube}`,
    'END:VCARD',
  ].join('\r\n')
}

export default function VCard() {
  const { language } = useLanguage()
  const cardRef = useRef<HTMLDivElement>(null)
  const [isVisible, setIsVisible] = useState(false)
  const [avatarPos, setAvatarPos] = useState({ x: 0, y: 0 })
  const avatarRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const el = cardRef.current
    if (!el) return
    const observer = new IntersectionObserver(
      ([e]) => setIsVisible(e.isIntersecting),
      { threshold: 0.15, rootMargin: '0px 0px -50px 0px' }
    )
    observer.observe(el)
    return () => observer.disconnect()
  }, [])

  const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    const el = avatarRef.current
    if (!el) return
    const rect = el.getBoundingClientRect()
    const cx = rect.left + rect.width / 2
    const cy = rect.top + rect.height / 2
    const dx = (e.clientX - cx) / 20
    const dy = (e.clientY - cy) / 20
    setAvatarPos({ x: Math.max(-8, Math.min(8, dx)), y: Math.max(-8, Math.min(8, dy)) })
  }, [])

  const handleMouseLeave = useCallback(() => setAvatarPos({ x: 0, y: 0 }), [])

  const handleDownloadVcf = () => {
    const blob = new Blob([generateVcf()], { type: 'text/vcard;charset=utf-8' })
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = `kevin-victor.vcf`
    a.click()
    URL.revokeObjectURL(a.href)
  }

  const handleShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: 'Kevin Victor - Real Estate',
          text: 'Contact card for Kevin Victor, Real Estate Professional at Hogar Realtors',
          url: typeof window !== 'undefined' ? window.location.href : '',
        })
      } catch (e) {
        if ((e as Error).name !== 'AbortError') {
          navigator.clipboard?.writeText(typeof window !== 'undefined' ? window.location.href : '')
        }
      }
    } else {
      navigator.clipboard?.writeText(typeof window !== 'undefined' ? window.location.href : '')
    }
  }

  const mapsUrl = encodeURIComponent(VCARD_DATA.address)

  return (
    <section
      id="vcard"
      ref={cardRef}
      className="py-16 sm:py-20 md:py-24 px-4 sm:px-6 relative overflow-hidden"
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      style={{
        // CSS custom properties for theming
        ['--vcard-primary' as string]: '#374527',
        ['--vcard-primary-light' as string]: '#4a5a35',
        ['--vcard-primary-dark' as string]: '#1D2019',
        ['--vcard-accent' as string]: '#C1BAB3',
      }}
    >
      <div className="container mx-auto max-w-2xl">
        <div
          className={`rounded-3xl overflow-hidden border-2 border-[var(--vcard-accent)] bg-white shadow-xl transition-all duration-1000 ${
            isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'
          }`}
        >
          {/* Hero header - animated gradient/noise background */}
          <div className="relative pt-12 sm:pt-16 pb-10 sm:pb-12 px-6 sm:px-10 bg-gradient-to-br from-[var(--vcard-primary)] via-[var(--vcard-primary-light)] to-[var(--vcard-primary-dark)] overflow-hidden">
            {/* Animated gradient overlay */}
            <div className="absolute inset-0 opacity-30">
              <div className="absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(193,186,179,0.15),transparent_50%)]" />
              <div className="absolute inset-0 bg-[radial-gradient(circle_at_70%_80%,rgba(0,0,0,0.2),transparent_50%)]" />
            </div>
            {/* Noise texture (CSS only) */}
            <div
              className="absolute inset-0 opacity-[0.03]"
              style={{
                backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`,
              }}
            />

            <div className="relative z-10 flex flex-col items-center text-center">
              {/* Avatar with glow ring */}
              <div
                ref={avatarRef}
                className="relative mb-6 sm:mb-8 transition-transform duration-300 ease-out"
                style={{ transform: `translate(${avatarPos.x}px, ${avatarPos.y}px)` }}
              >
                <div className="absolute -inset-2 rounded-full bg-white/20 animate-pulse blur-xl" />
                <div className="relative w-28 h-28 sm:w-36 sm:h-36 rounded-full overflow-hidden border-4 border-white/90 shadow-2xl ring-4 ring-white/30 ring-offset-4 ring-offset-[var(--vcard-primary)]">
                  <Image
                    src={imageUrls.about.kevin}
                    alt={VCARD_DATA.name}
                    fill
                    className="object-cover"
                    sizes="(max-width: 640px) 112px, 144px"
                  />
                </div>
                <div className="absolute -inset-1 rounded-full border-2 border-white/40 -z-10 opacity-60" />
              </div>

              <h2 className="text-2xl sm:text-3xl font-extrabold text-white uppercase tracking-tighter mb-1">
                {VCARD_DATA.name}
              </h2>
              <p className="text-sm sm:text-base uppercase tracking-widest text-white/90 font-semibold mb-1">
                {getTranslation(language, 'vcard.job') || VCARD_DATA.job}
              </p>
              <p className="text-xs sm:text-sm uppercase tracking-wider text-white/70">
                {VCARD_DATA.company}
              </p>
            </div>
          </div>

          {/* Action bar - Call | Email | Directions */}
          <div className="flex border-b border-[var(--vcard-accent)]/40 sticky top-0 z-20 bg-white">
            <a
              href={`tel:${VCARD_DATA.telRaw}`}
              className="flex-1 flex flex-col items-center gap-1.5 py-4 sm:py-5 text-[var(--vcard-primary)] hover:bg-[var(--vcard-primary)]/5 transition-all group"
              aria-label={getTranslation(language, 'vcard.call') || 'Call'}
            >
              <Phone size={22} className="group-hover:scale-110 transition-transform" />
              <span className="text-[10px] sm:text-xs font-bold uppercase tracking-widest">
                {getTranslation(language, 'vcard.call') || 'Call'}
              </span>
            </a>
            <a
              href={`mailto:${VCARD_DATA.email}`}
              className="flex-1 flex flex-col items-center gap-1.5 py-4 sm:py-5 text-[var(--vcard-primary)] hover:bg-[var(--vcard-primary)]/5 transition-all group border-x border-[var(--vcard-accent)]/40"
              aria-label={getTranslation(language, 'vcard.email') || 'Email'}
            >
              <Mail size={22} className="group-hover:scale-110 transition-transform" />
              <span className="text-[10px] sm:text-xs font-bold uppercase tracking-widest">
                {getTranslation(language, 'vcard.email') || 'Email'}
              </span>
            </a>
            <a
              href={`https://www.google.com/maps/search/?api=1&query=${mapsUrl}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex-1 flex flex-col items-center gap-1.5 py-4 sm:py-5 text-[var(--vcard-primary)] hover:bg-[var(--vcard-primary)]/5 transition-all group"
              aria-label={getTranslation(language, 'vcard.directions') || 'Directions'}
            >
              <MapPin size={22} className="group-hover:scale-110 transition-transform" />
              <span className="text-[10px] sm:text-xs font-bold uppercase tracking-widest">
                {getTranslation(language, 'vcard.directions') || 'Directions'}
              </span>
            </a>
          </div>

          {/* Contact details - staggered reveal */}
          <div className="px-6 sm:px-10 py-8 sm:py-10 space-y-6">
            <div
              className={`flex items-start gap-4 transition-all duration-500 ${
                isVisible ? 'opacity-100 translate-x-0' : 'opacity-0 -translate-x-4'
              }`}
              style={{ transitionDelay: '100ms' }}
            >
              <Phone size={20} className="text-[var(--vcard-primary)] shrink-0 mt-0.5" />
              <div>
                <p className="text-[10px] uppercase tracking-wider text-gray-500 mb-0.5">
                  {getTranslation(language, 'contactPage.phone')}
                </p>
                <a
                  href={`tel:${VCARD_DATA.telRaw}`}
                  className="text-base font-medium text-brand-text hover:text-[var(--vcard-primary)] transition-colors"
                >
                  {VCARD_DATA.mobile}
                </a>
              </div>
            </div>
            <div
              className={`flex items-start gap-4 transition-all duration-500 ${
                isVisible ? 'opacity-100 translate-x-0' : 'opacity-0 -translate-x-4'
              }`}
              style={{ transitionDelay: '200ms' }}
            >
              <Mail size={20} className="text-[var(--vcard-primary)] shrink-0 mt-0.5" />
              <div>
                <p className="text-[10px] uppercase tracking-wider text-gray-500 mb-0.5">
                  {getTranslation(language, 'contactPage.email')}
                </p>
                <a
                  href={`mailto:${VCARD_DATA.email}`}
                  className="text-base font-medium text-brand-text hover:text-[var(--vcard-primary)] transition-colors break-all"
                >
                  {VCARD_DATA.email}
                </a>
              </div>
            </div>
            <div
              className={`flex items-start gap-4 transition-all duration-500 ${
                isVisible ? 'opacity-100 translate-x-0' : 'opacity-0 -translate-x-4'
              }`}
              style={{ transitionDelay: '300ms' }}
            >
              <MapPin size={20} className="text-[var(--vcard-primary)] shrink-0 mt-0.5" />
              <div>
                <p className="text-[10px] uppercase tracking-wider text-gray-500 mb-0.5">
                  {getTranslation(language, 'contactPage.address')}
                </p>
                <a
                  href={`https://www.google.com/maps/search/?api=1&query=${mapsUrl}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-base font-medium text-brand-text hover:text-[var(--vcard-primary)] transition-colors"
                >
                  {VCARD_DATA.address}
                </a>
              </div>
            </div>
          </div>

          {/* Social media - animated icon grid with brand hover */}
          <div className="px-6 sm:px-10 pb-8">
            <div
              className={`flex justify-center gap-4 sm:gap-6 transition-all duration-500 ${
                isVisible ? 'opacity-100 scale-100' : 'opacity-0 scale-95'
              }`}
              style={{ transitionDelay: '400ms' }}
            >
              <a
                href={VCARD_DATA.facebook}
                target="_blank"
                rel="noopener noreferrer"
                className="w-12 h-12 rounded-full flex items-center justify-center bg-gray-100 text-[var(--vcard-primary)] hover:bg-[#1877f2] hover:text-white transition-all duration-300 hover:scale-110"
                aria-label="Facebook"
              >
                <Facebook size={22} />
              </a>
              <a
                href={VCARD_DATA.instagram}
                target="_blank"
                rel="noopener noreferrer"
                className="w-12 h-12 rounded-full flex items-center justify-center bg-gray-100 text-[var(--vcard-primary)] hover:bg-gradient-to-br hover:from-[#f09433] hover:via-[#dc2743] hover:to-[#bc1888] hover:text-white transition-all duration-300 hover:scale-110"
                aria-label="Instagram"
              >
                <Instagram size={22} />
              </a>
              <a
                href={VCARD_DATA.youtube}
                target="_blank"
                rel="noopener noreferrer"
                className="w-12 h-12 rounded-full flex items-center justify-center bg-gray-100 text-[var(--vcard-primary)] hover:bg-[#ff0000] hover:text-white transition-all duration-300 hover:scale-110"
                aria-label="YouTube"
              >
                <Youtube size={22} />
              </a>
            </div>
          </div>

          {/* CTA footer - Save Contact + Share */}
          <div className="px-6 sm:px-10 pb-8 sm:pb-10 flex flex-col sm:flex-row gap-3 sm:gap-4">
            <button
              onClick={handleDownloadVcf}
              className="flex-1 flex items-center justify-center gap-2 py-4 rounded-xl bg-[var(--vcard-primary)] text-white font-bold uppercase tracking-widest text-sm hover:bg-[var(--vcard-primary-dark)] transition-all active:scale-[0.98] hover:shadow-lg hover:shadow-[var(--vcard-primary)]/30"
            >
              <Download size={20} />
              {getTranslation(language, 'vcard.saveContact') || 'Save Contact'}
            </button>
            <button
              onClick={handleShare}
              className="flex-1 flex items-center justify-center gap-2 py-4 rounded-xl border-2 border-[var(--vcard-primary)] text-[var(--vcard-primary)] font-bold uppercase tracking-widest text-sm hover:bg-[var(--vcard-primary)]/10 transition-all active:scale-[0.98]"
            >
              <Share2 size={20} />
              {getTranslation(language, 'vcard.share') || 'Share'}
            </button>
          </div>
        </div>
      </div>
    </section>
  )
}
