"use client";

import Link from "next/link";
import { CmsNewsletterForm } from "./NewsletterForm";
import Image from "next/image";
import { useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  FaFacebookF,
  FaInstagram,
  FaXTwitter,
  FaYoutube,
  FaLinkedinIn,
} from "react-icons/fa6";

function getSocialIcon(platform?: string | null) {
  const key = platform?.toLowerCase() ?? "";
  if (key.includes("facebook")) return <FaFacebookF />;
  if (key.includes("instagram")) return <FaInstagram />;
  if (key.includes("youtube")) return <FaYoutube />;
  if (key.includes("linkedin")) return <FaLinkedinIn />;
  return <FaXTwitter />;
}

type FooterLink = {

  id?: string;
  label?: string | null;
  href?: string | null;
};

type SocialLink = FooterLink & {
  platform?: string | null;
};

type ScillyPageData = {
  included?: {
    forms?: Record<string, CmsNewsletterForm> | null;
    globals?: {
      footer?: {
        copyright?: string | null;
        legalLinks?: FooterLink[];
        socialLinks?: SocialLink[];
        newsletter?: {
          heading?: string | null;
          description?: string | null;
          form?: number | null;
        } | null;
        appLinks?: {
          appLabel?: string | null;
          iosUrl?: string | null;
          androidUrl?: string | null;
        } | null;
      } | null;
    } | null;
  } | null;
};

const fallbackSocialLinks: SocialLink[] = [
  { id: "facebook", platform: "facebook", href: "#", label: "Facebook" },
  { id: "instagram", platform: "instagram", href: "#", label: "Instagram" },
  { id: "x", platform: "x", href: "#", label: "X" },
  { id: "youtube", platform: "youtube", href: "#", label: "YouTube" },
  { id: "linkedin", platform: "linkedin", href: "#", label: "LinkedIn" },
];

const fallbackLegalLinks: FooterLink[] = [
  { id: "privacy", label: "Privacy Policy", href: "#" },
  { id: "terms", label: "Terms & Conditions", href: "#" },
];

function normalizeHref(href?: string | null) {
  if (!href) return "#";
  if (href.startsWith("#")) return href;
  if (href.startsWith("/") || href.startsWith("http://") || href.startsWith("https://")) {
    return href;
  }
  return `https://${href}`;
}


export default function ScillyNewsletterFooter({
  data,
}: {
  data: ScillyPageData;
}) {
  const [appTooltip, setAppTooltip] = useState<{ label: string; x: number; y: number } | null>(null);
  const appTimerRef = useRef<NodeJS.Timeout | null>(null);
  const footer = data.included?.globals?.footer;
  const copyright = footer?.copyright?.trim() || `©${new Date().getFullYear()} Karma Group`;
  const socialLinks =
    footer?.socialLinks && footer.socialLinks.length > 0
      ? footer.socialLinks
      : fallbackSocialLinks;
  const legalLinks =
    footer?.legalLinks && footer.legalLinks.length > 0
      ? footer.legalLinks
      : fallbackLegalLinks;
  const appLabel = footer?.appLinks?.appLabel?.trim() || "Karma Club App";
  const iosUrl = normalizeHref(footer?.appLinks?.iosUrl);
  const androidUrl = normalizeHref(footer?.appLinks?.androidUrl);



  return (
    <footer className="w-full h-auto lg:h-[150px] bg-[#1E1E1E] text-white" id="enquiry">
      <div className="mx-auto w-full max-w-[1680px] px-5 py-[40px] sm:px-8 md:px-12 md:py-[35px] xl:px-16 flex items-center h-full">
        <div className="grid w-full gap-7 justify-items-center text-center lg:grid-cols-[minmax(160px,0.18fr)_minmax(160px,0.22fr)_minmax(340px,0.39fr)_minmax(220px,0.21fr)] lg:items-center lg:justify-items-start lg:text-left xl:gap-10">
          <p className="text-[15px] text-white/90">{copyright}</p>

          <div className="flex items-center gap-[10px]">
            {socialLinks.map((item, index) => (
              <Link
                key={item.id ?? `${item.platform ?? "social"}-${index}`}
                href={normalizeHref(item.href)}
                aria-label={item.label?.trim() || item.platform || "Social link"}
                className="flex h-[28px] w-[28px] items-center justify-center rounded-full bg-white text-[13px] text-[#1E1E1E] transition hover:opacity-90"
              >
                {getSocialIcon(item.platform ?? item.label)}
              </Link>
            ))}
          </div>

          <div className="flex flex-col gap-7 lg:flex-row lg:items-center lg:gap-[20px]">
            <p className="text-[15px] text-white/90">{appLabel}</p>

            <div className="flex flex-wrap items-center justify-center gap-[10px] lg:justify-start">
              <div
                className="relative"
                onMouseMove={(e) => {
                  const r = e.currentTarget.getBoundingClientRect();
                  if (appTimerRef.current) clearTimeout(appTimerRef.current);
                  setAppTooltip(null);
                  appTimerRef.current = setTimeout(() => setAppTooltip({ label: "App Store", x: e.clientX - r.left, y: e.clientY - r.top }), 1000);
                }}
                onMouseLeave={() => { if (appTimerRef.current) clearTimeout(appTimerRef.current); setAppTooltip(null); }}
              >
                <Link href={iosUrl} className="flex h-[31px] items-center justify-center transition-transform hover:scale-111">
                  <Image
                    src="/scilly/appstore.svg"
                    alt="App Store"
                    width={111}
                    height={32}
                    className="h-full w-auto object-contain"
                    sizes="111px"
                    loading="lazy"
                  />
                </Link>
                <AnimatePresence>
                  {appTooltip?.label === "App Store" && (
                    <motion.div
                      initial={{ opacity: 0, scale: 0.95 }}
                      animate={{ opacity: 1, scale: 1 }}
                      exit={{ opacity: 0, scale: 0.95 }}
                      transition={{ duration: 0.12 }}
                      style={{ position: "absolute", left: appTooltip.x, top: appTooltip.y, transform: "translate(-50%, calc(-100% - 8px))", pointerEvents: "none", zIndex: 200, whiteSpace: "nowrap" }}
                      className="rounded border border-black bg-white px-3 py-1.5 text-sm font-semibold text-black shadow-sm"
                    >
                      App Store
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>

              <div
                className="relative"
                onMouseMove={(e) => {
                  const r = e.currentTarget.getBoundingClientRect();
                  if (appTimerRef.current) clearTimeout(appTimerRef.current);
                  setAppTooltip(null);
                  appTimerRef.current = setTimeout(() => setAppTooltip({ label: "Google Play", x: e.clientX - r.left, y: e.clientY - r.top }), 1000);
                }}
                onMouseLeave={() => { if (appTimerRef.current) clearTimeout(appTimerRef.current); setAppTooltip(null); }}
              >
                <Link href={androidUrl} className="flex h-[31px] items-center justify-center transition-transform hover:scale-111">
                  <Image
                    src="/scilly/playstore.svg"
                    alt="Google Play"
                    width={111}
                    height={32}
                    className="h-full w-auto object-contain"
                    sizes="111px"
                    loading="lazy"
                  />
                </Link>
                <AnimatePresence>
                  {appTooltip?.label === "Google Play" && (
                    <motion.div
                      initial={{ opacity: 0, scale: 0.95 }}
                      animate={{ opacity: 1, scale: 1 }}
                      exit={{ opacity: 0, scale: 0.95 }}
                      transition={{ duration: 0.12 }}
                      style={{ position: "absolute", left: appTooltip.x, top: appTooltip.y, transform: "translate(-50%, calc(-100% - 8px))", pointerEvents: "none", zIndex: 200, whiteSpace: "nowrap" }}
                      className="rounded border border-black bg-white px-3 py-1.5 text-sm font-semibold text-black shadow-sm"
                    >
                      Google Play
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            </div>
          </div>

          <div className="flex flex-wrap items-center justify-center gap-x-8 gap-y-3 lg:justify-end">
            {legalLinks.map((item, index) => (
              <Link
                key={item.id ?? `${item.label ?? "legal"}-${index}`}
                href={normalizeHref(item.href)}
                className="text-[15px] text-white/90 transition hover:text-white"
              >
                {item.label?.trim() || "Legal"}
              </Link>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
}