/**
 * Global Footer Component (React Server Component)
 *
 * Premium, SEO-optimized, dark-theme footer for ShineCode.
 * Dynamic Hydration via @shinecode/api-client:
 * - Top Categories: Filtered by "Select Category" from footer API setting (or live categories)
 * - Popular Services: Filtered by "Select Service" from footer API setting (or live popular services)
 * - Company Column: About Us, Blog, Become a Partner, Contact Support, Refund Policy, Data Deletion
 * - Corporate Bottom Bar: ONLY [Privacy Policy], [Terms of Service], [Sitemap], [Career]
 * - Configurations: Support Email, Phone, Social links & App Store badges
 */

import React from 'react';
import Link from 'next/link';
import { LanguageSwitcher } from './LanguageSwitcher';
import { ThemeToggle } from '@/components/ui/theme-toggle';
import {
  dashboardService,
  categoryService,
  getServices,
  type FooterSettings,
} from '@/lib/api/client';
import type { Category, Configurations, Service } from '@shinecode/api-client/types';

interface FooterProps {
  locale: string;
}

// Crisp Apple Icon SVG
function AppleStoreIcon({ className = 'w-6 h-6' }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M15.97 6.37c.61-.75 1.04-1.8 0.92-2.87-.9.04-1.97.6-2.6 1.34-.56.64-.99 1.7-0.85 2.72 1 .08 1.99-.51 2.53-1.19z" />
    </svg>
  );
}

// Authentic Multi-Color Google Play Icon SVG
function GooglePlayIcon({ className = 'w-5 h-5' }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path
        d="M3.609 1.814L13.792 12 3.61 22.186A2.38 2.38 0 013 21.232V2.768c0-.36.216-.696.609-.954z"
        fill="#00D3FF"
      />
      <path
        d="M17.265 8.528L13.792 12l3.473 3.472 3.882-2.206c1.38-.784 1.38-2.072 0-2.856l-3.882-2.206z"
        fill="#FFCE00"
      />
      <path
        d="M3.609 22.186L13.792 12 17.265 15.472 5.069 22.414c-.58.33-1.077.243-1.46-.228z"
        fill="#FF334B"
      />
      <path
        d="M17.265 8.528L13.792 12 3.609 1.814C3.992 1.343 4.489 1.256 5.069 1.586l12.196 6.942z"
        fill="#00E676"
      />
    </svg>
  );
}

// Instagram Icon SVG
function InstagramIcon({ className = 'w-5 h-5' }: { className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect width="20" height="20" x="2" y="2" rx="5" ry="5" />
      <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" />
      <line x1="17.5" x2="17.51" y1="6.5" y2="6.5" />
    </svg>
  );
}

// TikTok Icon SVG
function TikTokIcon({ className = 'w-5 h-5' }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M19.59 6.69a4.83 4.83 0 01-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 01-5.2 1.74 2.89 2.89 0 012.31-4.64c.298-.002.595.042.88.13V9.4a6.33 6.33 0 00-.88-.06A6.34 6.34 0 003.15 15.7a6.34 6.34 0 0010.86 4.45V11.22a8.16 8.16 0 004.88 1.6v-3.48a4.85 4.85 0 01-.7-.15 4.83 4.83 0 01-.6-.5z" />
    </svg>
  );
}

// Facebook Icon SVG
function FacebookIcon({ className = 'w-5 h-5' }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
    </svg>
  );
}

// LinkedIn Icon SVG
function LinkedinIcon({ className = 'w-5 h-5' }: { className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z" />
      <rect width="4" height="12" x="2" y="9" />
      <circle cx="4" cy="4" r="2" />
    </svg>
  );
}

// YouTube Icon SVG
function YouTubeIcon({ className = 'w-5 h-5' }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
    </svg>
  );
}

export async function Footer({ locale = 'en' }: FooterProps) {
  const isAr = locale === 'ar';

  // ── 1. Resilient Parallel Data Fetching ──
  let configurations: Configurations = {};
  let footerSettings: FooterSettings = {};
  let allCategories: Category[] = [];
  let allServices: Service[] = [];

  try {
    const [configsResult, footerSettingsResult, categoriesResult, servicesResult] =
      await Promise.all([
        dashboardService.getConfigurations({
          next: { revalidate: 86400, tags: ['configurations'] },
        }),
        dashboardService.getFooterSettings({
          next: { revalidate: 86400, tags: ['footer-setting'] },
        }),
        categoryService.getCategories(
          { per_page: 'all' },
          { next: { revalidate: 86400, tags: ['categories'] } }
        ),
        getServices(),
      ]);

    if (configsResult.ok && configsResult.data) {
      configurations = configsResult.data;
    }
    if (footerSettingsResult.ok && footerSettingsResult.data) {
      footerSettings = footerSettingsResult.data;
    }
    if (categoriesResult.ok && Array.isArray(categoriesResult.data)) {
      allCategories = categoriesResult.data;
    }
    if (servicesResult.ok && Array.isArray(servicesResult.data)) {
      allServices = servicesResult.data;
    }
  } catch (error) {
    console.error('[Footer] Error fetching dynamic data from API:', error);
  }

  // ── 2. Top Categories from "Select Category" Footer API ──
  const selectedCatIds = footerSettings.category_id || [];
  type NavItem = { id: number; name: string; slug: string };
  let displayCategories: NavItem[] = [];

  if (selectedCatIds.length > 0 && allCategories.length > 0) {
    // Preserve ordering from category_id array
    displayCategories = selectedCatIds
      .map((idStr) => allCategories.find((c) => String(c.id) === String(idStr)))
      .filter((c): c is Category => Boolean(c))
      .map((c) => ({ id: c.id, name: c.name, slug: c.slug }));
  }

  // Fallback if footer setting has no categories
  if (displayCategories.length === 0) {
    displayCategories = allCategories
      .slice(0, 6)
      .map((c) => ({ id: c.id, name: c.name, slug: c.slug }));
  }

  if (displayCategories.length === 0) {
    displayCategories = [
      { id: 9, name: isAr ? 'السبا والمساج' : 'SPA & Massage', slug: 'spa' },
      { id: 10, name: isAr ? 'العناية بالبشرة' : 'Skin Care', slug: 'skin-care' },
      { id: 11, name: isAr ? 'الرموش والحواجب' : 'Lashes & Eyebrows', slug: 'lashes-eyebrows' },
      { id: 12, name: isAr ? 'العناية بالأظافر' : 'Nail Care', slug: 'nail-care' },
      { id: 13, name: isAr ? 'العناية بالشعر' : 'Hair Care', slug: 'hair-care' },
    ];
  }

  // ── 3. Popular Services from "Select Service" Footer API ──
  const selectedServiceIds = footerSettings.service_id || [];
  let displayServices: NavItem[] = [];

  if (selectedServiceIds.length > 0 && allServices.length > 0) {
    // Preserve ordering from service_id array
    displayServices = selectedServiceIds
      .map((idStr) => allServices.find((s) => String(s.id) === String(idStr)))
      .filter((s): s is Service => Boolean(s))
      .map((s) => ({ id: s.id, name: s.name, slug: s.slug }));
  }

  // Fallback to top rated / featured services if needed
  if (displayServices.length === 0) {
    displayServices = allServices
      .filter((s) => s.is_featured === 1)
      .slice(0, 6)
      .map((s) => ({ id: s.id, name: s.name, slug: s.slug }));
  }

  if (displayServices.length === 0) {
    displayServices = allServices
      .slice(0, 6)
      .map((s) => ({ id: s.id, name: s.name, slug: s.slug }));
  }

  if (displayServices.length === 0) {
    displayServices = [
      { id: 161, name: isAr ? 'قص شعر رجالي' : 'Men’s Haircut', slug: 'mens-haircut' },
      { id: 39, name: isAr ? 'مساج الأحجار الساخنة' : 'Hot Stone Massage', slug: 'hot-stone-massage' },
      { id: 29, name: isAr ? 'رفع وتصفيح الرموش' : 'Lash Lift / Lamination', slug: 'lash-lift-lamination' },
      { id: 24, name: isAr ? 'قص وتسريح الشعر' : 'Hair Cut', slug: 'hair-cut' },
      { id: 22, name: isAr ? 'بديكير جيليش فاخر' : 'Gelish Pedicure', slug: 'gelish-pedicure' },
    ];
  }

  // ── 4. System Configurations (Support, Socials, Stores) ──
  const supportEmail = configurations.inquiry_email || 'contact@shinecode.ae';
  const supportPhone = configurations.helpline_number || '+971 4329 8815';
  const appStoreUrl =
    configurations.appstore_url ||
    'https://apps.apple.com/us/app/shinecode-home-beauty-salon/id1661355199';
  const playStoreUrl =
    configurations.playstore_url ||
    'https://play.google.com/store/apps/details?id=com.shinecode.user';
  const copyrightText =
    configurations.site_copyright ||
    (isAr ? '© 2026 SHINECODE L.L.C-FZ. جميع الحقوق محفوظة.' : '© 2026 SHINECODE L.L.C-FZ. All rights reserved.');

  const socialLinks = [
    {
      name: 'Instagram',
      url: configurations.instagram_url || 'https://www.instagram.com/shinecode_uae/',
      icon: InstagramIcon,
    },
    {
      name: 'Facebook',
      url: configurations.facebook_url || 'https://facebook.com/ShineCodeUAE',
      icon: FacebookIcon,
    },
    {
      name: 'TikTok',
      url: configurations.twitter_url || 'https://www.tiktok.com/@shinecode',
      icon: TikTokIcon,
    },
    {
      name: 'LinkedIn',
      url:
        configurations.linkedin_url ||
        'https://www.linkedin.com/company/shinecode-professional-home-beauty-services/',
      icon: LinkedinIcon,
    },
    {
      name: 'YouTube',
      url: configurations.youtube_url || null,
      icon: YouTubeIcon,
    },
  ].filter((item) => Boolean(item.url && item.url.trim().length > 0));

  // ── 5. Company Column (Company Navigation & Policies) ──
  const company = [
    { name: isAr ? 'من نحن' : 'About Us', href: `/${locale}/about` },
    { name: isAr ? 'المدونة' : 'Blog', href: `/${locale}/blog` },
    { name: isAr ? 'انضم كخبير (شركاء النجاح)' : 'Become a Partner (Pros)', href: `/${locale}/partner` },
    { name: isAr ? 'مركز الدعم والمساعدة' : 'Contact Support', href: `/${locale}/contact` },
    { name: isAr ? 'سياسة الاسترجاع والإلغاء' : 'Refund Policy', href: `/${locale}/refund-policy` },
    { name: isAr ? 'طلب حذف البيانات' : 'Data Deletion', href: `/${locale}/data-deletion` },
  ];

  return (
    <footer className="bg-zinc-950 text-zinc-400 py-16 w-full border-t border-zinc-900 mt-auto">
      <div className="max-w-7xl mx-auto px-4 lg:px-8">
        {/* ── Main 5-Column Grid ── */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-12">
          {/* ── Columns 1 & 2: Brand & Dedicated App Download (Span 2 cols) ── */}
          <div className="col-span-1 md:col-span-2 lg:col-span-2 space-y-4 text-start">
            <Link
              href={`/${locale}`}
              className="inline-flex items-center gap-1.5 text-2xl font-bold text-white tracking-tight"
            >
              <span>Shine</span>
              <span className="text-brand-500">Code</span>
            </Link>

            <p className="mt-4 text-sm leading-relaxed text-zinc-400 max-w-md">
              {isAr
                ? 'خدمات التجميل والعناية الفاخرة، تصلك حتى باب منزلك في دبي والشارقة وعجمان. التجربة الأرقى على الإطلاق.'
                : 'Premium beauty and wellness delivered directly to your doorstep across Dubai, Sharjah, and Ajman. The ultimate luxury experience.'}
            </p>

            {/* Support Direct Contact (Email & Phone from API) */}
            <div className="pt-1 text-xs space-y-1.5 text-zinc-400">
              <div className="flex items-center gap-2">
                <span className="text-zinc-500 font-medium">{isAr ? 'البريد الإلكتروني:' : 'Email:'}</span>
                <a
                  href={`mailto:${supportEmail}`}
                  className="hover:text-white transition-colors underline-offset-4 hover:underline"
                >
                  {supportEmail}
                </a>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-zinc-500 font-medium">{isAr ? 'الهاتف المباشر:' : 'Phone:'}</span>
                <a
                  href={`tel:${supportPhone.replace(/\s+/g, '')}`}
                  className="hover:text-white transition-colors underline-offset-4 hover:underline"
                  dir="ltr"
                >
                  {supportPhone}
                </a>
              </div>
            </div>

            {/* App Download CTA Section */}
            <div className="pt-4">
              <h3 className="text-white font-semibold text-base mb-4">
                {isAr ? 'حمل التطبيق الآن' : 'Download the App'}
              </h3>

              <div className="flex flex-wrap items-center gap-3">
                {/* App Store Badge */}
                <a
                  href={appStoreUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-3 bg-zinc-900 hover:bg-zinc-800 border border-zinc-800 hover:border-zinc-700 rounded-lg px-4 py-2 text-white transition-colors cursor-pointer shadow-sm group"
                >
                  <AppleStoreIcon className="w-5 h-5 shrink-0 group-hover:text-white transition-colors" />
                  <div className="text-start leading-tight">
                    <div className="text-[10px] text-zinc-400 font-normal">
                      {isAr ? 'متوفر على' : 'Download on the'}
                    </div>
                    <div className="text-xs font-bold tracking-tight text-white">App Store</div>
                  </div>
                </a>

                {/* Google Play Badge */}
                <a
                  href={playStoreUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-3 bg-zinc-900 hover:bg-zinc-800 border border-zinc-800 hover:border-zinc-700 rounded-lg px-4 py-2 text-white transition-colors cursor-pointer shadow-sm group"
                >
                  <GooglePlayIcon className="w-5 h-5 shrink-0 group-hover:scale-105 transition-transform" />
                  <div className="text-start leading-tight">
                    <div className="text-[10px] text-zinc-400 font-normal">
                      {isAr ? 'احصل عليه من' : 'GET IT ON'}
                    </div>
                    <div className="text-xs font-bold tracking-tight text-white">Google Play</div>
                  </div>
                </a>
              </div>
            </div>

            {/* Language Switcher & Theme Toggle */}
            <div className="pt-2 flex items-center gap-3">
              <LanguageSwitcher currentLocale={locale} theme="dark" />
              <ThemeToggle themeStyle="dark" />
            </div>
          </div>

          {/* ── Column 3: Top Categories (Hydrated from Select Category Footer API) ── */}
          <div className="text-start">
            <h3 className="text-white font-semibold text-base mb-6">
              {isAr ? 'أبرز التصنيفات' : 'Top Categories'}
            </h3>
            <ul className="flex flex-col gap-3 text-sm">
              {displayCategories.map((category) => (
                <li key={category.id}>
                  <Link
                    href={`/${locale}/categories/${category.slug || category.id}`}
                    className="text-zinc-400 hover:text-white transition-colors inline-block"
                  >
                    {category.name}
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          {/* ── Column 4: Popular Services (Hydrated from Select Service Footer API) ── */}
          <div className="text-start">
            <h3 className="text-white font-semibold text-base mb-6">
              {isAr ? 'الخدمات الأكثر طلباً' : 'Popular Services'}
            </h3>
            <ul className="flex flex-col gap-3 text-sm">
              {displayServices.map((service) => (
                <li key={service.id}>
                  <Link
                    href={`/${locale}/services/${service.slug || service.id}`}
                    className="text-zinc-400 hover:text-white transition-colors inline-block"
                  >
                    {service.name}
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          {/* ── Column 5: Company & Trust ── */}
          <div className="text-start">
            <h3 className="text-white font-semibold text-base mb-6">
              {isAr ? 'الشركة' : 'Company'}
            </h3>
            <ul className="flex flex-col gap-3 text-sm">
              {company.map((item, idx) => (
                <li key={idx}>
                  <Link
                    href={item.href}
                    className="text-zinc-400 hover:text-white transition-colors inline-block"
                  >
                    {item.name}
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        </div>

        {/* ── Bottom Bar: Corporate, Legal & Social ── */}
        <div className="mt-16 pt-8 border-t border-zinc-900 flex flex-col md:flex-row justify-between items-center gap-4">
          {/* Left: Copyright */}
          <p className="text-xs text-zinc-500">{copyrightText}</p>

          {/* Center: ONLY [Privacy Policy] [Terms of Service] [Sitemap] [Career] */}
          <div className="flex flex-wrap items-center gap-6 text-xs text-zinc-400">
            <Link href={`/${locale}/privacy`} className="hover:text-white transition-colors">
              {isAr ? 'سياسة الخصوصية' : 'Privacy Policy'}
            </Link>
            <Link href={`/${locale}/terms`} className="hover:text-white transition-colors">
              {isAr ? 'شروط الخدمة' : 'Terms of Service'}
            </Link>
            <Link href="/sitemap.xml" target="_blank" className="hover:text-white transition-colors">
              {isAr ? 'خريطة الموقع' : 'Sitemap'}
            </Link>
            <Link href={`/${locale}/careers`} className="hover:text-white transition-colors">
              {isAr ? 'الوظائف' : 'Career'}
            </Link>
          </div>

          {/* Right: Dynamic Social Media Icons */}
          <div className="flex items-center gap-5 text-zinc-400">
            {socialLinks.map((social) => {
              const Icon = social.icon;
              return (
                <a
                  key={social.name}
                  href={social.url!}
                  target="_blank"
                  rel="noopener noreferrer"
                  aria-label={`ShineCode on ${social.name}`}
                  className="hover:text-white transition-colors"
                >
                  <Icon className="w-5 h-5" />
                </a>
              );
            })}
          </div>
        </div>
      </div>
    </footer>
  );
}

export default Footer;
