"use client";

import { externalHref } from "@/features/events/eventLifecycle";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";
import { useLanguageStore } from "@/store/languageStore";
import { useHomeCms } from "@/features/cms/hooks/useHomeCms";
import { pickLocalized, type FooterCms } from "@/features/shared";
import { SOCIAL_LINKS } from "./footerLinks";
import { footerPageLinks } from "./footerPages";


interface FooterProps {
  /**
   * Admin-editable footer content (`GET /home/` → `footer`), fetched by the
   * layout on the server. Missing CMS fields fall back to the original React
   * footer content. Omit it entirely (client-only trees, for example
   * `app/not-found.tsx`) and the footer fetches the payload itself from the
   * shared React Query cache.
   */
  footer?: FooterCms | null;
}


export default function Footer({ footer }: FooterProps) {
  const { t } = useTranslation();
  const pathname = usePathname();
  const language = useLanguageStore((s) => s.language);
  const { cms } = useHomeCms({ enabled: footer === undefined });

  const data = footer ?? cms?.footer ?? null;
  const pageLinks = footerPageLinks(data?.pages, language, t);
  /* Admin-managed (`site_settings.*_url`): an account the admin has cleared is
     not shown. A bundled default URL used to stand in, so a cleared account
     could never be taken off the footer. */
  const socials = SOCIAL_LINKS.map((link) => ({
    ...link,
    // http(s) only, scheme added when the admin typed `www.…`.
    href: externalHref(data?.social?.[link.key]) ?? "",
  })).filter((link) => link.href !== "");
  const copyright =
    pickLocalized(data?.copyright_en, data?.copyright_ar, language) ||
    t("COMMON.ALL.RIGHTS.RESERVED", { year: new Date().getFullYear() });

  return (
    <footer className="bg-primary-5 text-white">
      <div className="2xl:w-[88%] laptop:w-[88%] laptopmain:w-[90%] w-[95%] mobilescreen:w-[100%] mdscreen:w-[100%] mx-auto">
        <div className="footer-main items-center pt-[70px] mobilescreen:pt-[40px] mobilescreen:gap-[0] gap-8 lg:gap-0 mdscreen:gap-0 flex flex-col 2xl:flex-row lg:flex-row mdscreen:flex-col sm:lg:flex-row justify-between">
          {/* Logo */}
          <div className="w-[15%] mobilescreen:mx-auto mobilescreen:pb-[40px] pb-[40px] mdscreen:border-b mobilescreen:border-b mobilescreen:border-b-white mobilescreen:flex mobilescreen:w-[100%] mobilescreen:justify-center mdscreen:flex mdscreen:w-[100%] mdscreen:justify-center">
            <Image
              className="w-[85px] h-[100px] object-contain"
              src="/assets/auth/fotterlogo.svg"
              alt="Fursa Logo"
              width={85}
              height={100}
            />
          </div>

          {/* Links */}
          <nav className="footer-page-links">
            {pageLinks.map((page) => (
              <Link
                key={page.slug}
                href={page.href}
                className={`hover:underline block text-center whitespace-nowrap ${
                  pathname === page.href ? "font-bold" : ""
                }`}
              >
                {page.label.replace(/[:：]/gu, "").trim()}
              </Link>
            ))}
            <Link
              href="/faq"
              className={`hover:underline block text-center whitespace-nowrap ${pathname === "/faq" ? "font-bold" : ""}`}
            >
              {t("COMMON.FAQ")}
            </Link>
            <Link href="/contact-us" className="hover:underline block text-center whitespace-nowrap">
              {t("COMMON.CONTACTUS")}
            </Link>
          </nav>

          {/* Social Icons — CMS URLs only; the block hides when there are none. */}
          {socials.length > 0 && <div className="mobilescreen:w-[60%] mobilescreen:mx-auto mobilescreen:pt-[40px] mobilescreen:border-t mdscreen:w-[60%] mdscreen:mx-auto mdscreen:pt-[40px] mdscreen:border-t">
            <p className="text-lg font-bold text-center">{t("COMMON.FOLLOWUS")}</p>
            <div className="flex items-center gap-7 extrasmall:gap-3 mt-4 mdscreen:mt-0 pt-5 mobilescreen:justify-center mdscreen:justify-center">
              {socials.map(({ key, label, className, href, Icon }) => (
                <a
                  key={key}
                  className={className}
                  href={href}
                  target="_blank"
                  rel="noopener noreferrer"
                  aria-label={label}
                >
                  <Icon />
                </a>
              ))}
            </div>
          </div>}
        </div>

        {/* Copyright — CMS text with the React footer's localized fallback. */}
        <div className="text-center text-base pb-[70px] mobilescreen:pt-[30px] mdscreen:pt-[30px]">
          {copyright}
        </div>
      </div>
    </footer>
  );
}
