'use client'
import { useLanguage } from '@/contexts/LanguageContext';
import { motion } from 'framer-motion';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useInView } from 'framer-motion';
import { Facebook, Twitter, Instagram, Linkedin, Mail, Phone, MapPin, GraduationCap, Users } from 'lucide-react';
import Link from 'next/link';
import { portalRequest } from '@/services/data/portal-api';
import { resolveMediaUrl } from '@/services/shared/media-url';

type FooterProfile = {
  siteName?: string
  siteNameAr?: string
  siteNameEn?: string
  siteDescriptionAr?: string
  siteDescriptionEn?: string
  contactPhone?: string
  contactEmail?: string
  addressAr?: string
  addressEn?: string
  mapLocation?: string
  socialLinks?: any
  facebook?: string
  twitter?: string
  instagram?: string
  linkedin?: string
  footerBackgroundType?: string
  footerBackgroundImage?: string
  footerBackgroundVideo?: string
  footerBackgroundOverlayOpacity?: string | number
}

type FooterSocialLink = {
  key: 'facebook' | 'twitter' | 'instagram' | 'linkedin'
  icon: typeof Facebook
  href: string
  label: string
}

function asText(value: unknown): string {
  return typeof value === 'string' ? value.trim() : value == null ? '' : String(value).trim();
}

function asUrl(value: unknown): string {
  const raw = asText(value);
  if (!raw) return '';
  if (/^https?:\/\//i.test(raw)) return raw;
  if (raw.startsWith('//')) return `https:${raw}`;
  if (raw.startsWith('www.')) return `https://${raw}`;
  return raw;
}

function detectPlatform(label: string, url: string): FooterSocialLink['key'] | '' {
  const source = `${label} ${url}`.toLowerCase();
  if (source.includes('facebook') || source.includes('فيس')) return 'facebook';
  if (source.includes('instagram') || source.includes('انست') || source.includes('إنست')) return 'instagram';
  if (source.includes('linkedin') || source.includes('لينكد')) return 'linkedin';
  if (source.includes('twitter') || source.includes('تويتر') || source.includes('x.com')) return 'twitter';
  return '';
}

function normalizePhoneHref(phone: string): string {
  const cleaned = phone.replace(/[^\d+]/g, '');
  if (!cleaned) return 'tel:+964XXXXXXXX';
  return `tel:${cleaned}`;
}

function hasLatin(text: string): boolean {
  return /[A-Za-z]/.test(text);
}

function pickEnglish(value: string, fallback: string): string {
  const trimmed = asText(value);
  if (trimmed && hasLatin(trimmed)) return trimmed;
  return fallback;
}

export const Footer = () => {
  const { t, language } = useLanguage();
  const currentYear = new Date().getFullYear();
  const footerRef = useRef(null);
  const isInView = useInView(footerRef, { once: true, margin: "-50px" });
  const [profile, setProfile] = useState<FooterProfile | null>(null);

  useEffect(() => {
    let mounted = true;
    portalRequest<any>('/api/aau/profile')
      .then((data) => {
        if (!mounted || !data || typeof data !== 'object') return;
        setProfile(data as FooterProfile);
      })
      .catch(() => {
        if (mounted) setProfile(null);
      });
    return () => {
      mounted = false;
    };
  }, []);

  const socialLinks = useMemo<FooterSocialLink[]>(() => {
    const defaults: FooterSocialLink[] = [
      { key: 'facebook', icon: Facebook, href: 'https://facebook.com/ngu.edu.iq', label: t('فيسبوك', 'Facebook') },
      { key: 'twitter', icon: Twitter, href: 'https://twitter.com/ngu_edu_iq', label: t('تويتر', 'Twitter') },
      { key: 'instagram', icon: Instagram, href: 'https://instagram.com/ngu.edu.iq', label: t('إنستغرام', 'Instagram') },
      { key: 'linkedin', icon: Linkedin, href: 'https://linkedin.com/school/ngu-edu-iq', label: t('لينكدإن', 'LinkedIn') },
    ];

    const byKey: Record<string, string> = {};

    const rawSocial = profile?.socialLinks;
    if (Array.isArray(rawSocial)) {
      rawSocial.forEach((entry: any) => {
        const url = asUrl(entry?.url);
        const label = asText(entry?.labelAr || entry?.labelEn || entry?.label);
        const key = detectPlatform(label, url);
        if (key && url) byKey[key] = url;
      });
    } else if (rawSocial && typeof rawSocial === 'object') {
      byKey.facebook = asUrl((rawSocial as any).facebook);
      byKey.twitter = asUrl((rawSocial as any).twitter);
      byKey.instagram = asUrl((rawSocial as any).instagram);
      byKey.linkedin = asUrl((rawSocial as any).linkedin);
    }

    if (!byKey.facebook) byKey.facebook = asUrl(profile?.facebook);
    if (!byKey.twitter) byKey.twitter = asUrl(profile?.twitter);
    if (!byKey.instagram) byKey.instagram = asUrl(profile?.instagram);
    if (!byKey.linkedin) byKey.linkedin = asUrl(profile?.linkedin);

    return defaults.map((item) => ({
      ...item,
      href: byKey[item.key] || item.href,
    }));
  }, [profile, t]);

  const footerBackgroundType = asText(profile?.footerBackgroundType).toLowerCase();
  const footerBackgroundImage = resolveMediaUrl(profile?.footerBackgroundImage);
  const footerBackgroundVideo = resolveMediaUrl(profile?.footerBackgroundVideo);
  const footerOverlayOpacityValue = Number(profile?.footerBackgroundOverlayOpacity);
  const footerOverlayOpacity = Number.isFinite(footerOverlayOpacityValue)
    ? Math.max(0, Math.min(1, footerOverlayOpacityValue))
    : 0.65;
  const hasImageBackground = footerBackgroundType === 'image' && Boolean(footerBackgroundImage);
  const hasVideoBackground = footerBackgroundType === 'video' && Boolean(footerBackgroundVideo);

  const siteNameAr = asText(profile?.siteNameAr) || 'جامعة الجيل الجديد';
  const siteNameEn = pickEnglish(
    asText(profile?.siteNameEn || profile?.siteName),
    'AJ JEEL ALJADEED UNIVERSITY'
  );
  const siteDescriptionAr = asText(profile?.siteDescriptionAr)
    || 'مؤسسة تعليمية رائدة تهدف إلى إعداد خريجين متخصصين ومؤهلين علميًا وتقنيًا للمساهمة في تنمية المجتمع.';
  const siteDescriptionEn = pickEnglish(
    asText(profile?.siteDescriptionEn),
    'A leading educational institution aiming to prepare specialized and scientifically qualified graduates to contribute to community development.'
  );
  const addressLabel = t(
    asText(profile?.addressAr) || 'صنعاء، اليمن',
    pickEnglish(asText(profile?.addressEn), 'Sanaa, Yemen')
  );
  const mapLocation = asUrl(profile?.mapLocation) || 'https://maps.google.com/?q=Sanaa,Yemen';
  const contactPhone = asText(profile?.contactPhone) || '+964 XXX XXX XXXX';
  const phoneHref = normalizePhoneHref(contactPhone);
  const contactEmail = asText(profile?.contactEmail) || 'info@ngu.edu.iq';
  const emailHref = `mailto:${contactEmail}`;

  const quickLinks = [
    { ar: 'الكليات', en: 'Colleges', href: '/colleges' },
    { ar: 'القبول', en: 'Admission', href: '/admission' },
    { ar: 'الأخبار', en: 'News', href: '/news' },
    { ar: 'تواصل معنا', en: 'Contact', href: '/contact' },
  ];

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1,
        delayChildren: 0.2
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.5,
        ease: "easeOut" as const
      }
    }
  };

  return (
    <footer className="bg-primary text-primary-foreground relative overflow-hidden" ref={footerRef}>
      {(hasImageBackground || hasVideoBackground) && (
        <div className="absolute inset-0">
          {hasImageBackground && (
            <img
              src={footerBackgroundImage}
              alt=""
              className="h-full w-full object-cover"
              loading="lazy"
            />
          )}
          {hasVideoBackground && (
            <video
              className="h-full w-full object-cover"
              src={footerBackgroundVideo}
              autoPlay
              muted
              loop
              playsInline
              preload="metadata"
            />
          )}
          <div
            className="absolute inset-0 bg-primary"
            style={{ opacity: footerOverlayOpacity }}
          />
        </div>
      )}

      {/* Animated Background */}
      <div className="absolute inset-0 overflow-hidden">
        <motion.div
          className="absolute -top-20 -right-20 w-64 h-64 bg-secondary/10 rounded-full blur-3xl"
          animate={{
            scale: [1, 1.2, 1],
            opacity: [0.3, 0.5, 0.3]
          }}
          transition={{
            duration: 6,
            repeat: Infinity,
            ease: "easeInOut"
          }}
        />
        <motion.div
          className="absolute -bottom-20 -left-20 w-72 h-72 bg-secondary/10 rounded-full blur-3xl"
          animate={{
            scale: [1, 1.3, 1],
            opacity: [0.2, 0.4, 0.2]
          }}
          transition={{
            duration: 8,
            repeat: Infinity,
            ease: "easeInOut",
            delay: 2
          }}
        />
      </div>

      <div className="container mx-auto px-4 py-12 relative z-10">
        <motion.div
          className="grid md:grid-cols-4 gap-8 mb-8"
          variants={containerVariants}
          initial="hidden"
          animate={isInView ? "visible" : "hidden"}
        >
          {/* Logo & Description */}
          <motion.div variants={itemVariants} className="md:col-span-2">
            <motion.div
              className="flex items-center gap-3 mb-4"
              whileHover={{ scale: 1.02 }}
            >
              <motion.div
                className="w-14 h-14 bg-secondary rounded-xl flex items-center justify-center"
                whileHover={{ rotate: 360 }}
                transition={{ duration: 0.6 }}
              >
                <GraduationCap className="w-8 h-8 text-primary" />
              </motion.div>
              <div>
                <h3 className="text-2xl font-display font-bold text-secondary">
                  {t(siteNameAr, siteNameEn)}
                </h3>
                <p className="text-sm text-primary-foreground/70">AAU</p>
              </div>
            </motion.div>
            <p className="text-primary-foreground/80 leading-relaxed max-w-md">
              {t(siteDescriptionAr, siteDescriptionEn)}
            </p>
          </motion.div>

          {/* Quick Links */}
          <motion.div variants={itemVariants}>
            <h4 className="text-lg font-bold text-secondary mb-4">
              {t('روابط سريعة', 'Quick Links')}
            </h4>
            <nav className="space-y-2">
              {quickLinks.map((link, index) => (
                <motion.a
                  key={index}
                  href={link.href}
                  className="block text-primary-foreground/80 hover:text-secondary transition-colors"
                  whileHover={{ x: language === 'ar' ? -5 : 5 }}
                  transition={{ duration: 0.2 }}
                >
                  {t(link.ar, link.en)}
                </motion.a>
              ))}
            </nav>
          </motion.div>

          {/* Location & Contact Info */}
          <motion.div variants={itemVariants}>
            <h4 className="text-lg font-bold text-secondary mb-6">
              {t('تواصل معنا', 'Contact Us')}
            </h4>
            <div className="space-y-4">
              {/* Mini Map Card */}
              <motion.div 
                className="bg-white/5 backdrop-blur-md border border-white/10 rounded-2xl overflow-hidden group/map cursor-pointer h-24 relative"
                whileHover={{ scale: 1.02 }}
                onClick={() => window.open(mapLocation, '_blank', 'noopener,noreferrer')}
              >
                <div className="absolute inset-0 bg-[url('https://images.unsplash.com/photo-1526778548025-fa2f459cd5c1?w=400&q=80')] bg-cover bg-center opacity-40 group-hover/map:opacity-60 transition-opacity" />
                <div className="absolute inset-0 bg-gradient-to-t from-primary/90 to-transparent" />
                <div className="relative p-3 h-full flex items-end">
                  <div className="flex items-center gap-2 text-white">
                    <div className="p-1.5 bg-secondary rounded-lg shadow-lg">
                      <MapPin className="w-4 h-4 text-primary" />
                    </div>
                    <div>
                      <p className="text-[10px] text-white/60 uppercase tracking-wider font-bold">{t('الموقع', 'Location')}</p>
                      <p className="text-xs font-bold leading-tight">{addressLabel}</p>
                    </div>
                  </div>
                </div>
              </motion.div>

              <div className="space-y-3 pt-2">
                <motion.a
                  href={phoneHref}
                  className="flex items-center gap-3 text-primary-foreground/70 hover:text-secondary transition-colors group"
                  whileHover={{ x: language === 'ar' ? -5 : 5 }}
                >
                  <div className="w-8 h-8 rounded-full bg-white/5 flex items-center justify-center group-hover:bg-secondary group-hover:text-primary transition-all">
                    <Phone className="w-4 h-4" />
                  </div>
                  <span className="text-sm font-medium">{contactPhone}</span>
                </motion.a>
                <motion.a
                  href={emailHref}
                  className="flex items-center gap-3 text-primary-foreground/70 hover:text-secondary transition-colors group"
                  whileHover={{ x: language === 'ar' ? -5 : 5 }}
                >
                  <div className="w-8 h-8 rounded-full bg-white/5 flex items-center justify-center group-hover:bg-secondary group-hover:text-primary transition-all">
                    <Mail className="w-4 h-4" />
                  </div>
                  <span className="text-sm font-medium">{contactEmail}</span>
                </motion.a>
              </div>
            </div>
          </motion.div>
        </motion.div>

        {/* Divider */}
        <motion.div
          className="h-px bg-gradient-to-r from-transparent via-secondary/50 to-transparent mb-8"
          initial={{ scaleX: 0 }}
          animate={isInView ? { scaleX: 1 } : { scaleX: 0 }}
          transition={{ duration: 0.8, delay: 0.5 }}
        />

        {/* Bottom Section */}
        <motion.div
          className="flex flex-col md:flex-row items-center justify-between gap-4"
          initial={{ opacity: 0, y: 20 }}
          animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
          transition={{ delay: 0.6, duration: 0.5 }}
        >
          {/* Social Links Cards */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 w-full md:w-auto">
            {socialLinks.map((social, index) => (
              <motion.a
                key={index}
                href={social.href}
                className="flex items-center gap-3 p-2.5 rounded-2xl bg-white/5 border border-white/10 hover:bg-secondary hover:text-primary transition-all duration-300 group"
                target="_blank"
                rel="noopener noreferrer"
                whileHover={{ y: -5, scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                initial={{ opacity: 0, y: 20 }}
                animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
                transition={{ delay: 0.7 + index * 0.1, duration: 0.3 }}
                aria-label={social.label}
              >
                <div className="w-10 h-10 rounded-xl bg-white/5 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                  <social.icon className="w-5 h-5" />
                </div>
                <div>
                  <p className="text-xs font-bold uppercase group-hover:text-primary transition-colors">{social.label}</p>
                </div>
              </motion.a>
            ))}
          </div>

          {/* Copyright */}
          <div className="flex flex-col items-center gap-4">
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 10 }}
              transition={{ delay: 0.9, duration: 0.5 }}
            >
              <Link 
                href="/team" 
                className="group relative inline-flex items-center gap-2 px-8 py-2.5 bg-secondary text-primary font-bold rounded-full overflow-hidden transition-all duration-300 hover:shadow-lg hover:shadow-secondary/20 hover:scale-105"
              >
                <Users className="w-4 h-4" />
                <span>{t('فريق العمل', 'Our Team')}</span>
              </Link>
            </motion.div>
            <motion.p
              className="text-sm text-primary-foreground/70 text-center"
              initial={{ opacity: 0 }}
              animate={isInView ? { opacity: 1 } : { opacity: 0 }}
              transition={{ delay: 1, duration: 0.5 }}
            >
              © {currentYear} {t('جامعة الجيل الجديد. جميع الحقوق محفوظة.', 'AJ JEEL ALJADEED UNIVERSITY. All rights reserved.')}
            </motion.p>
          </div>
        </motion.div>
      </div>
    </footer>
  );
};
