"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import {
  Mail,
  Phone,
  MapPin,
  Facebook,
  Instagram,
  Youtube,
  ArrowRight,
  ShieldCheck,
} from "lucide-react";
import { useLanguage } from "@/lib/i18n";
import { apiRequest, apiUrl } from "@/lib/api";
import { isSettingEnabled, type WebsiteSettings } from "@/lib/website-settings";

const footerLinks = {
  quickLinks: [
    { name: "common.home", href: "/" },
    { name: "common.findGuides", href: "/guides" },
    { name: "common.blog", href: "/blogs" },
    { name: "common.aboutUs", href: "/#about-us" },
    { name: "common.sitemap", href: "/sitemap" },
    {
      name: "common.contactUs",
      href: "https://uttarakhandtourism.gov.in/page/contact-us",
      isExternal: true,
    },
    { name: "common.registerAsGuide", href: "/auth/register" },
    { name: "common.signIn", href: "/auth/login" },
  ],
  destinations: [
    { name: "Char Dham", href: "/guides?expertise=Char+Dham+Pilgrimage" },
    { name: "Adventure", href: "/guides?expertise=Adventure+Tourism" },
    { name: "Wildlife", href: "/guides?expertise=Wildlife+Safari" },
    { name: "Cultural", href: "/guides?expertise=Cultural+Heritage" },
  ],
  contact: [
    {
      icon: MapPin,
      text: "Uttarakhand Tourism Development Board, Pt. Deen Dayal Upadhyay Paryatan Bhawan Near ONGC Helipad, Garhi Cantt, Dehradun, Uttarakhand 248001",
    },
    { icon: Phone, text: "+91 135-2559898, 2559987" },
    {
      icon: Mail,
      text: "publicityutdb@gmail.com | publicityofficer@utdbofficial.com",
    },
  ],
};

function LinkedinIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden="true"
      className={className}
      fill="currentColor"
    >
      <path d="M4.98 3.5C4.98 4.88 3.86 6 2.5 6S0 4.88 0 3.5 1.12 1 2.5 1s2.48 1.12 2.48 2.5ZM.3 8h4.4v15H.3V8Zm7.4 0h4.2v2.05h.06c.58-1.1 2.02-2.25 4.16-2.25 4.45 0 5.27 2.93 5.27 6.74V23h-4.38v-7.5c0-1.79-.03-4.1-2.5-4.1-2.5 0-2.88 1.95-2.88 3.97V23H7.7V8Z" />
    </svg>
  );
}

function PinterestIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden="true"
      className={className}
      fill="currentColor"
    >
      <path d="M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.174-.105-.949-.199-2.403.041-3.439.219-.937 1.407-5.965 1.407-5.965s-.359-.72-.359-1.781c0-1.669.967-2.914 2.171-2.914 1.023 0 1.518.769 1.518 1.69 0 1.029-.655 2.568-.994 3.995-.283 1.194.599 2.169 1.777 2.169 2.134 0 3.772-2.249 3.772-5.495 0-2.873-2.064-4.882-5.012-4.882-3.414 0-5.418 2.561-5.418 5.207 0 1.031.397 2.138.893 2.739.098.119.112.224.083.345-.091.379-.293 1.194-.333 1.361-.053.22-.174.266-.402.161-1.499-.698-2.436-2.889-2.436-4.649 0-3.785 2.75-7.262 7.929-7.262 4.163 0 7.398 2.967 7.398 6.931 0 4.136-2.607 7.464-6.227 7.464-1.216 0-2.359-.631-2.748-1.378l-.747 2.848c-.271 1.042-1.002 2.349-1.492 3.146 1.123.347 2.312.535 3.55.535 6.624 0 11.99-5.367 11.99-11.988C24.007 5.367 18.641.001 12.017.001Z" />
    </svg>
  );
}

const socialLinks = [
  {
    icon: Instagram,
    href: "https://www.instagram.com/uttarakhand_tourismofficial",
    label: "Instagram",
  },
  {
    icon: LinkedinIcon,
    href: "https://www.linkedin.com/company/uttarakhand_tourismofficial",
    label: "LinkedIn",
  },
  {
    icon: PinterestIcon,
    href: "https://in.pinterest.com/utdbtourism/",
    label: "Pinterest",
  },
  {
    icon: Facebook,
    href: "https://www.facebook.com/UttarakhandTourismOfficialPage",
    label: "Facebook",
  },
  {
    icon: Youtube,
    href: "https://www.youtube.com/channel/UCX7c5KGrPjG8tzna7xhro4g",
    label: "Youtube",
  },
];

type VisitorActivityResponse = {
  data?: unknown;
  visitor_count?: number | string;
  visitorCount?: number | string;
  total_visitors?: number | string;
  totalVisitors?: number | string;
  count?: number | string;
  total?: number | string;
};

const visitorCountPath = "/website/visitors/count";
const defaultContactEmail =
  "publicityutdb@gmail.com | publicityofficer@utdbofficial.com";
const defaultContactPhone = "+91 135-2559898, 2559987";
const defaultOfficialAddress =
  "Uttarakhand Tourism Development Board, Pt. Deen Dayal Upadhyay Paryatan Bhawan Near ONGC Helipad, Garhi Cantt, Dehradun, Uttarakhand 248001";

function getCountValue(value: unknown): number | null {
  const count = Number(value);
  return Number.isFinite(count) && count >= 0 ? count : null;
}

function getVisitorCount(data: unknown): number | null {
  if (!data || typeof data !== "object") {
    return null;
  }

  const response = data as VisitorActivityResponse;
  const directCount =
    getCountValue(response.visitor_count) ??
    getCountValue(response.visitorCount) ??
    getCountValue(response.total_visitors) ??
    getCountValue(response.totalVisitors) ??
    getCountValue(response.count) ??
    getCountValue(response.total);

  if (directCount !== null) {
    return directCount;
  }

  return getVisitorCount(response.data);
}

function toVisitorDigits(count: number) {
  return String(Math.max(0, Math.floor(count)))
    .padStart(8, "0")
    .split("");
}

function getVisitorDevice() {
  if (typeof window === "undefined") {
    return "desktop";
  }

  const userAgent = navigator.userAgent.toLowerCase();

  if (
    /mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(userAgent)
  ) {
    return "mobile";
  }

  if (/ipad|tablet/.test(userAgent)) {
    return "tablet";
  }

  return window.innerWidth < 768 ? "mobile" : "desktop";
}

export function Footer({ settings = {} }: { settings?: WebsiteSettings }) {
  const { language, t } = useLanguage();
  const [visitorCount, setVisitorCount] = useState(0);
  const visitorCountEnabled =
    settings.visitor_count_status === undefined
      ? true
      : isSettingEnabled(settings.visitor_count_status);
  const visitorDigits = useMemo(
    () => toVisitorDigits(visitorCount),
    [visitorCount],
  );
  const contactItems = useMemo(
    () => [
      {
        icon: MapPin,
        text: settings.official_address || defaultOfficialAddress,
      },
      { icon: Phone, text: settings.contact_phone || defaultContactPhone },
      { icon: Mail, text: settings.contact_email || defaultContactEmail },
    ],
    [settings],
  );
  const visibleSocialLinks = useMemo(
    () =>
      socialLinks
        .map((social) => {
          const settingsKey = `${social.label.toLowerCase()}_url`;

          return {
            ...social,
            href: settings[settingsKey] || social.href,
          };
        })
        .filter((social) => Boolean(social.href)),
    [settings],
  );

  useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }

    if (!visitorCountEnabled) {
      return;
    }

    const recordVisitorActivity = async () => {
      try {
        const response = await apiRequest(
          apiUrl("/website/visitor-activities"),
          {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              country: "India",
              device: getVisitorDevice(),
            }),
            dedupe: false,
            skipAuth: true,
          },
        );

        if (!response.ok) {
          throw new Error("Visitor activity request failed.");
        }
      } catch {
        // Keep the page usable if visitor tracking is unavailable.
      }
    };

    const fetchVisitorCount = async () => {
      try {
        const response = await apiRequest(apiUrl(visitorCountPath), {
          method: "GET",
          headers: {
            Accept: "application/json",
          },
          skipAuth: true,
        });

        if (!response.ok) {
          return;
        }

        const result = (await response.json()) as VisitorActivityResponse;
        const nextCount = getVisitorCount(result);

        if (nextCount !== null) {
          setVisitorCount(nextCount);
        }
      } catch {
        // Keep the zero-padded fallback if the count endpoint is unavailable.
      }
    };

    void recordVisitorActivity().finally(fetchVisitorCount);
  }, [visitorCountEnabled]);

  return (
    <footer
      id="contact-us"
      className="relative overflow-visible bg-[var(--theme-dark)]"
    >
      <div
        className="pointer-events-none absolute inset-x-0 top-0 z-20 h-24 -translate-y-[78%] bg-repeat-x"
        style={{
          backgroundImage: "url('/footer-border.png')",
          backgroundPosition: "bottom center",
          backgroundSize: "auto 100%",
        }}
      />
      <div className="absolute left-0 top-0 h-72 w-72 rounded-full bg-[var(--theme-secondary)]/10 blur-3xl" />
      <div className="absolute bottom-0 right-0 h-72 w-72 rounded-full bg-[var(--theme-accent)]/10 blur-3xl" />

      <div className="container mx-auto px-4 py-16 relative">
        <div className="grid grid-cols-1 gap-10 md:grid-cols-2 lg:grid-cols-[1.2fr_0.8fr_0.8fr_1.25fr]">
          {/* Brand */}
          <div className="space-y-6">
            <Link
              href="/"
              className="inline-block transition-opacity hover:opacity-85"
            >
              <Image
                src="/footer-logo.png"
                alt="Uttarakhand Tourism Development Board"
                width={510}
                height={58}
                className="h-20 w-auto object-contain"
              />
            </Link>
            <p className="text-sm text-white/70 leading-relaxed">
              {t("common.footerDescription")}
            </p>
            <div className="inline-flex items-center gap-3 rounded-full border border-[var(--theme-border-strong)] bg-white px-4 py-2.5 shadow-[0_10px_30px_color-mix(in_srgb,var(--theme-secondary)_12%,transparent)]">
              <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-[var(--theme-secondary)] to-[var(--theme-accent)] text-white shadow-md shadow-[var(--theme-secondary)]/25">
                <ShieldCheck className="h-5 w-5" />
              </div>
              <div>
                <p className="text-sm font-black text-foreground">
                  {t("common.verifiedGuideNetwork")}
                </p>
                <p className="text-xs font-medium text-[var(--theme-primary)]">
                  {t("common.trustedByTourism")}
                </p>
              </div>
            </div>
            {/* Social Links */}
            <div className="flex items-center gap-3">
              {visibleSocialLinks.map((social) => (
                <a
                  key={social.label}
                  href={social.href}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex h-10 w-10 items-center justify-center rounded-full border border-white/10 bg-white/10 text-white/70 transition-all hover:-translate-y-0.5 hover:border-[var(--theme-secondary)]/50 hover:bg-white/15 hover:text-[var(--theme-secondary)] hover:shadow-md"
                  aria-label={social.label}
                >
                  <social.icon className="h-4 w-4" />
                </a>
              ))}
            </div>
          </div>

          {/* Quick Links */}
          <div>
            <h3 className="font-black text-white mb-5 text-sm uppercase tracking-wider">
              {t("common.quickLinks")}
            </h3>
            <ul className="space-y-3">
              {footerLinks.quickLinks.map((link) => (
                <li key={link.name}>
                  {link.isExternal ? (
                    <a
                      href={link.href}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="group inline-flex items-center gap-2 text-sm font-medium text-white/70 transition-colors hover:text-[var(--theme-secondary)]"
                    >
                      <ArrowRight className="h-3.5 w-3.5 text-[var(--theme-secondary)] transition-transform group-hover:translate-x-1" />
                      {t(link.name)}
                    </a>
                  ) : (
                    <Link
                      href={link.href}
                      className="group inline-flex items-center gap-2 text-sm font-medium text-white/70 transition-colors hover:text-[var(--theme-secondary)]"
                    >
                      <ArrowRight className="h-3.5 w-3.5 text-[var(--theme-secondary)] transition-transform group-hover:translate-x-1" />
                      {t(link.name)}
                    </Link>
                  )}
                </li>
              ))}
            </ul>
          </div>

          {/* Destinations */}
          <div>
            <h3 className="font-black text-white mb-5 text-sm uppercase tracking-wider">
              {t("common.explore")}
            </h3>
            <ul className="space-y-3">
              {footerLinks.destinations.map((link) => (
                <li key={link.name}>
                  <Link
                    href={link.href}
                    className="group inline-flex items-center gap-2 text-sm font-medium text-white/70 transition-colors hover:text-[var(--theme-secondary)]"
                  >
                    <ArrowRight className="h-3.5 w-3.5 text-[var(--theme-secondary)] transition-transform group-hover:translate-x-1" />
                    {link.name}
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          {/* Contact */}
          <div>
            <h3 className="font-black text-white mb-5 text-sm uppercase tracking-wider">
              {t("common.contactUs")}
            </h3>
            <ul className="space-y-3">
              {contactItems.map((item, index) => (
                <li key={index}>
                  <span className="group inline-flex items-start gap-2 text-sm font-medium leading-6 text-white/70 transition-colors hover:text-[var(--theme-secondary)]">
                    <item.icon className="mt-1 h-3.5 w-3.5 shrink-0 text-[var(--theme-secondary)]" />
                    {item.text}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        </div>

        {/* Bottom */}
        <div className="mt-12 pt-8 border-t border-white/10">
          <div className="grid grid-cols-1 items-center gap-6 lg:grid-cols-[1fr_auto_1fr]">
            <p className="text-center text-sm text-white/60 lg:text-left">
              &copy; {new Date().getFullYear()}{" "}
              <span className="ml-1"> {t("common.copyright")}</span>
            </p>

            {visitorCountEnabled ? (
              <div
                className="flex w-full max-w-[260px] flex-col items-center px-3 py-2 text-center sm:max-w-[280px]"
                aria-label="Visitors Who Discovered Us"
              >
                <div className="flex items-center justify-center gap-0.5">
                  {visitorDigits.map((digit, index) => (
                    <span
                      key={`${digit}-${index}`}
                      className="flex h-6 w-5 items-center justify-center rounded-[3px] bg-gradient-to-b from-[var(--theme-secondary)] to-[var(--theme-primary-dark)] text-[1.05rem] font-light leading-none text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.28),0_1px_2px_rgb(0_0_0/0.16)] sm:h-7 sm:w-6 sm:text-[1.2rem]"
                    >
                      {digit}
                    </span>
                  ))}
                </div>
                <p className="mt-1.5 text-[12px] font-semibold leading-none text-[var(--theme-secondary)]">
                  Visitors Who Discovered Us
                </p>
              </div>
            ) : (
              <div aria-hidden="true" />
            )}

            <div className="flex flex-col items-center gap-4 lg:items-end">
              <div className="flex items-center gap-6">
                <a
                  href="https://uttarakhandtourism.gov.in/page/policy-and-guidelines"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm text-white/60 hover:text-[var(--theme-secondary)] transition-colors"
                >
                  {t("common.policyGuidelines")}
                </a>
                <Link
                  href="#"
                  className="text-sm text-white/60 hover:text-[var(--theme-secondary)] transition-colors"
                >
                  {t("common.termsOfService")}
                </Link>
              </div>
              <div className="flex items-center justify-center text-xs font-semibold text-white/60 sm:justify-end">
                <span className="mr-1">{t("common.designedBy")}</span>
                <svg
                  className="h-[15px] w-4 mr-1"
                  viewBox="0 0 16 15"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  aria-hidden="true"
                >
                  <path
                    d="M1.05947 1.32367C0.51397 1.86916 1.16973 2.69421 1.56579 3.03855C1.75972 3.02714 2.18347 3.00548 2.32699 3.01011C2.50639 3.0159 2.69447 2.86543 3.00409 2.88569C3.3137 2.90594 3.22689 2.89148 3.43233 3.05641C3.63778 3.22134 3.64646 3.35445 3.63488 3.49913C3.62331 3.6438 3.51975 3.70262 3.40204 3.71978C3.28434 3.73695 3.21813 3.64131 3.05138 3.58491C2.91798 3.53979 2.81278 3.67537 2.77685 3.7488H2.23806C2.31096 3.86438 2.49092 4.14676 2.62748 4.35161C2.79819 4.60767 2.5464 4.70234 2.70025 5.15499C2.8541 5.60763 3.58914 6.53141 4.23017 7.22372C4.8712 7.91603 5.96033 8.06479 6.50266 8.15755C7.04498 8.25032 6.92354 8.64729 6.99611 8.81888C7.06868 8.99048 7.37575 9.6744 7.50613 9.73488C7.63651 9.79535 7.70053 9.87721 7.89726 10.0148C8.05465 10.1249 8.20912 10.3701 8.26667 10.4789C8.14595 10.5536 7.87177 10.7406 7.74084 10.8913C7.57718 11.0796 7.3178 12.043 7.18742 12.2023C7.05704 12.3617 5.72428 12.4558 4.98546 12.9194C4.39441 13.2902 3.79273 14.286 3.56578 14.7375H8.53467C8.56848 14.4767 8.64477 13.9349 8.67954 13.8538C8.723 13.7524 8.35522 13.6437 8.22321 13.5713C8.09121 13.4989 8.23045 13.4482 8.58538 13.0932C8.9403 12.7383 9.50888 12.6028 10.2458 12.3677C10.9827 12.1326 10.8476 11.8826 10.7901 11.8279C10.7327 11.7731 9.83934 10.7765 9.77055 10.7655C9.70176 10.7545 9.38192 10.9846 8.92813 11.0801C8.47435 11.1757 7.89637 11.7823 7.70053 11.8826C7.50468 11.9829 7.58111 11.6199 7.60499 11.4479C7.6241 11.3104 8.1131 10.8423 8.35522 10.6254C8.37588 10.6048 8.41722 10.5465 8.41722 10.4789C8.41722 10.3943 8.13539 9.93215 7.85097 9.73488C7.56654 9.5376 7.27842 9.11594 7.2177 9.04308C7.15698 8.97021 7.16103 8.75567 7.17317 8.67471C7.18531 8.59375 7.17317 8.55731 7.27842 8.56946C7.38367 8.5816 7.49284 8.64729 7.74084 8.91759C7.98885 9.18789 8.76668 9.49251 8.99777 9.54324C9.22887 9.59397 9.35872 9.73841 9.4584 9.61596C9.55807 9.49351 10.1974 8.797 10.3735 8.64729C10.5496 8.49758 10.444 8.17175 9.55453 7.99562C8.66509 7.8195 8.07093 7.28694 7.85097 7.10082C7.63101 6.9147 7.86789 6.88086 8.11323 6.73703C8.35858 6.59321 8.04555 5.71336 8.25706 5.60337C8.46856 5.49339 8.49394 5.75566 8.73083 5.76412C8.96771 5.77258 8.94606 5.54415 9.4584 5.15499C9.97074 4.76582 10.5159 3.58986 10.6682 3.29375C10.8205 2.99765 11.1589 2.84457 11.8442 2.73538C12.5294 2.62619 15.6883 2.02921 15.8399 1.95925C15.9915 1.88929 14.6506 1.45786 12.7383 1.06142C10.8261 0.664976 9.14342 0.747638 8.94606 0.790811C8.7487 0.833983 8.86588 0.85248 8.1998 0.846313C7.53371 0.840145 7.26234 1.2842 7.213 1.52473C7.16366 1.76526 6.78128 2.54237 6.63943 2.84457C6.49758 3.14678 5.88182 3.77265 5.61214 4.02104C5.34246 4.26943 5.19343 3.97846 5.10827 3.85072C5.02311 3.72297 3.63214 2.332 3.31989 2.17587C3.00763 2.01975 1.74134 0.641795 1.05947 1.32367Z"
                    fill="currentColor"
                  />
                </svg>
                <span>{t("common.drishInfotech")}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </footer>
  );
}
