import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Linkedin, Instagram, Youtube, Facebook, Mail, Phone, ArrowUpRight, CalendarDays, ArrowUp, MapPin } from "lucide-react";
import Logo from "./Logo";
import { COMPANY, CERTIFICATIONS, SOCIAL_HREFS } from "../data/site";
import { SOLUTIONS } from "../data/solutions";
import { openMeetingModal } from "./MeetingModal";
import MagneticButton from "./MagneticButton";

/** Live platform status — real health probe, not decoration. */
function useSystemStatus() {
  const [state, setState] = useState<"checking" | "ok" | "down">("checking");
  useEffect(() => {
    let alive = true;
    fetch(`${process.env.REACT_APP_BACKEND_URL}/api/health`)
      .then((r) => alive && setState(r.ok ? "ok" : "down"))
      .catch(() => alive && setState("down"));
    return () => {
      alive = false;
    };
  }, []);
  return state;
}

export default function Footer({ social }: { social?: Record<string, string> | null }) {
  // DB settings win, but "#" placeholders (or missing keys) fall back to the real profiles.
  const pick = (key: string) => (social?.[key] && social[key] !== "#" ? social[key] : SOCIAL_HREFS[key]);
  const socials = [
    { name: "LinkedIn", Icon: Linkedin, href: pick("linkedin") },
    { name: "Instagram", Icon: Instagram, href: pick("instagram") },
    { name: "Facebook", Icon: Facebook, href: pick("facebook") },
    { name: "YouTube", Icon: Youtube, href: pick("youtube") },
  ];
  const status = useSystemStatus();

  return (
    <footer className="relative bg-[#050B14] overflow-hidden" data-testid="site-footer">
      <div className="grain" aria-hidden="true" />
      {/* Giant watermark wordmark */}
      <p
        aria-hidden="true"
        className="pointer-events-none select-none absolute -bottom-8 right-0 font-display font-bold leading-[0.78] tracking-[-0.03em] text-outline-white opacity-[0.07] text-[26vw] lg:text-[15rem]"
      >
        AVIOKAN
      </p>
      <div className="absolute -top-24 left-1/4 h-56 w-56 rounded-full bg-cy/10 blur-[110px] pointer-events-none" aria-hidden="true" />

      <div className="relative mx-auto max-w-[1320px] px-5 md:px-10 pt-10 pb-4">
        {/* ── Editorial CTA band ── */}
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6 pb-8 border-b border-white/10" data-testid="footer-cta-band">
          <Link to="/contact" className="group" data-testid="footer-cta-link">
            <p className="text-[10px] font-tech tracking-[0.3em] text-ember mb-2.5 flex items-center gap-3">
              <span className="h-px w-8 bg-ember/60 inline-block" />
              START A PROJECT
            </p>
            <p className="font-display font-black text-[2.1rem] md:text-[2.9rem] text-white leading-[0.98] tracking-tight">
              Let&apos;s build <span className="text-white/40 group-hover:text-cy transition-colors duration-500">what&apos;s next.</span>
            </p>
          </Link>
          <div className="flex flex-wrap items-center gap-3">
            <MagneticButton>
              <Link to="/contact" className="inline-flex items-center gap-2 bg-ember text-white font-bold text-[13px] px-6 py-3 hover:bg-[#E54D16] transition-colors" data-testid="footer-talk-to-expert">
                Talk to an Expert <ArrowUpRight size={15} />
              </Link>
            </MagneticButton>
            <MagneticButton>
              <button onClick={openMeetingModal} className="inline-flex items-center gap-2 border border-white/20 bg-white/5 backdrop-blur-md text-white font-bold text-[13px] px-6 py-3 hover:bg-white/10 hover:border-cy/50 transition-colors" data-testid="footer-book-meeting">
                <CalendarDays size={15} /> Book a Consultation
              </button>
            </MagneticButton>
          </div>
        </div>

        {/* ── Link grid ── */}
        <div className="grid grid-cols-2 md:grid-cols-12 gap-x-8 gap-y-8 py-8">
          <div className="col-span-2 md:col-span-4">
            <Logo size="sm" light />
            <p className="mt-2.5 text-[10px] font-tech tracking-[0.24em] text-ember">INTEGRATE. INNOVATE. TRANSFORM.</p>
            <div className="mt-3 space-y-1.5 text-[12px]">
              <a href={`mailto:${COMPANY.email}`} className="flex items-center gap-2 text-white/65 hover:text-cy transition-colors group" data-testid="footer-email-link">
                <span className="h-5 w-5 grid place-items-center border border-white/15 group-hover:border-cy/50 transition-colors"><Mail size={10} className="text-cy" /></span>
                {COMPANY.email}
              </a>
              <a href={`tel:${COMPANY.phoneHref}`} className="flex items-center gap-2 text-white/65 hover:text-cy transition-colors group" data-testid="footer-phone-link">
                <span className="h-5 w-5 grid place-items-center border border-white/15 group-hover:border-cy/50 transition-colors"><Phone size={10} className="text-cy" /></span>
                {COMPANY.phone}
              </a>
              <p className="flex items-start gap-2 text-white/40 leading-snug max-w-[250px]">
                <span className="h-5 w-5 grid place-items-center border border-white/15 shrink-0"><MapPin size={10} className="text-white/50" /></span>
                {COMPANY.addressShort}
              </p>
            </div>
            <div className="mt-3.5 flex gap-1.5">
              {socials.map(({ name, Icon, href }) => (
                <a key={name} href={href} target="_blank" rel="noopener noreferrer" aria-label={name} title={name}
                  className="h-8 w-8 grid place-items-center border border-white/15 text-white/70 hover:text-ink hover:bg-cy hover:border-cy hover:-translate-y-0.5 transition-all duration-200" data-testid={`footer-social-${name.toLowerCase()}`}>
                  <Icon size={13} />
                </a>
              ))}
            </div>
          </div>

          <FooterCol title="Solutions" className="md:col-span-3">
            {SOLUTIONS.map((s) => (
              <Link key={s.slug} to={`/solutions/${s.slug}`} className="footer-link !text-[12px] flex items-baseline gap-2 group/sol" data-testid={`footer-solution-link-${s.slug}`}>
                <span className="font-tech text-[9px] text-ember">{s.num}</span>
                <span className="group-hover/sol:translate-x-0.5 transition-transform duration-200">{s.shortTitle}</span>
              </Link>
            ))}
          </FooterCol>

          <FooterCol title="Company" className="md:col-span-2">
            {[
              { to: "/about", label: "About" },
              { to: "/about/mission-vision", label: "Mission & Vision" },
              { to: "/about/approach", label: "Our Approach" },
              { to: "/about/blog", label: "Blog" },
              { to: "/about/careers", label: "Careers" },
              { to: "/digital-engineering", label: "Digital Engineering" },
              { to: "/partners", label: "Technology Partners" },
              { to: "/clients", label: "Clients" },
            ].map((l) => (
              <Link key={l.to + l.label} to={l.to} className="footer-link !text-[12px] flex items-center justify-between gap-2 w-full group/co" data-testid={`footer-company-link-${l.label.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`}>
                {l.label}
                <ArrowUpRight size={10} className="text-white/25 group-hover/co:text-cy transition-colors" />
              </Link>
            ))}
          </FooterCol>

          <FooterCol title="Credentials" className="col-span-2 md:col-span-3">
            {/* natural-width chips that wrap — cannot collide at any column width */}
            <div className="flex flex-wrap gap-1 w-full">
              {CERTIFICATIONS.map((c) => (
                <span key={c.name} className={`inline-flex items-center gap-1 border px-1.5 py-1 text-[8.5px] font-tech whitespace-nowrap ${c.status === "registered" ? "border-cy/25 text-cy" : "border-ember/35 text-ember"}`} title={`${c.name} — ${c.type}`}>
                  <img src={c.logo} alt="" className="h-3 w-3 shrink-0 object-contain" loading="lazy" />
                  {c.name}
                </span>
              ))}
            </div>
            <div className="mt-2.5 flex flex-wrap items-center gap-2.5">
              {/* Live platform status — real probe of the public health endpoint */}
              <span className="inline-flex items-center gap-2 border border-white/12 bg-white/[0.04] px-2.5 py-1.5" data-testid="footer-system-status" title="Live status of the aviokan.com platform">
                <span className="relative flex h-1.5 w-1.5" aria-hidden="true">
                  {status === "ok" && <><span className="absolute inline-flex h-full w-full rounded-full bg-cy opacity-60 animate-ping" /><span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-cy" /></>}
                  {status === "checking" && <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-white/30" />}
                  {status === "down" && <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-ember" />}
                </span>
                <span className="font-tech text-[8.5px] tracking-[0.18em] text-white/55">
                  {status === "ok" ? "ALL SYSTEMS OPERATIONAL" : status === "checking" ? "CHECKING STATUS…" : "STATUS CHECK FAILED"}
                </span>
              </span>
              <p className="text-[9.5px] text-white/35 leading-snug">9 registrations — ISO on roadmap</p>
            </div>
          </FooterCol>
        </div>
      </div>

      {/* ── Legal strip ── */}
      <div className="border-t border-white/10 relative">
        <div className="mx-auto max-w-[1320px] px-5 md:px-10 py-3 flex flex-col sm:flex-row gap-2 items-center justify-between text-[11px] text-white/40">
          <p>© 2026 {COMPANY.name}. All Rights Reserved.</p>
          <div className="flex flex-wrap gap-x-5 gap-y-1 justify-center">
            <Link to="/privacy-policy" className="hover:text-cy transition-colors">Privacy</Link>
            <Link to="/terms-conditions" className="hover:text-cy transition-colors">Terms</Link>
            <Link to="/cookie-policy" className="hover:text-cy transition-colors">Cookies</Link>
            <Link to="/disclaimer" className="hover:text-cy transition-colors">Disclaimer</Link>
          </div>
          <button
            onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
            aria-label="Back to top"
            title="Back to top"
            data-testid="footer-back-to-top"
            className="h-7 w-7 grid place-items-center border border-white/15 text-white/60 hover:text-cy hover:border-cy/60 hover:-translate-y-0.5 transition-all duration-200"
          >
            <ArrowUp size={13} />
          </button>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, children, className = "" }: { title: string; children: React.ReactNode; className?: string }) {
  return (
    <div className={className}>
      <h3 className="text-[9.5px] font-tech tracking-[0.3em] text-cy mb-3 flex items-center gap-2">
        <span className="h-px w-4 bg-cy/50 inline-block" aria-hidden="true" />
        {title.toUpperCase()}
      </h3>
      <div className="flex flex-col items-start gap-1.5">{children}</div>
    </div>
  );
}
