// src/sections/FooterSection.tsx
import React, { useMemo } from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import {
  s_Text14_400 as Text14_400,
  s_Text12_400 as Text12_400,
} from "../Typography";
import { useSingleton, useCollection } from "cms/factory";

/* ============ CMS selections ============ */

type CmsSystem = {
  id: string;
  footerLogo?: { url?: string | null } | null;
  linedUrl?: string | null;
};

type CmsNavItem = {
  id: string;
  label: string;
  href: string;
  order: number;
  enabled?: boolean;
  children?: CmsNavItem[];
};

const SYS_SEL = `
  id
  footerLogo { url }
  linedUrl
`;

const NAV_SEL = `
  id label href order enabled
  children { id label href order enabled }
`;

/* ============ Component ============ */

const FooterSection: React.FC = () => {
  const { data: system } = useSingleton<CmsSystem>("System", SYS_SEL);
  const { data: navItems } = useCollection<CmsNavItem>("NavItem", NAV_SEL);

  const logoSrc = system?.footerLogo?.url || "/imgs/logo.svg";
  const linkedinUrl = system?.linedUrl || "#";
  const year = new Date().getFullYear();

  const items = useMemo(() => {
    if (!navItems) return [];
    const roots = navItems
      .filter(i => i.enabled !== false && !(i as any).parent)
      .sort((a, b) => a.order - b.order);
    roots.forEach(r => {
      r.children = (r.children ?? [])
        .filter(c => c.enabled !== false)
        .sort((a, b) => a.order - b.order);
    });
    return roots;
  }, [navItems]);

  return (
    <Wrap>
      <Inner>
        <Top>
          <LogoRow>
            <Logo
              onClick={() => (window.location.href = "/#freedom")}
              style={{ cursor: "pointer" }}
              src={logoSrc}
              alt="Logo"
            />
          </LogoRow>

          {/* Копирайт — отдельная секция, чтобы на мобиле идти выше меню */}
          <CopyMobile>{`© ${year} Freedom Telecom International. All Rights Reserved`}</CopyMobile>

          <Nav>
            {items.map(i => (
              <NavLink key={i.id} href={i.href}>
                {i.label}
              </NavLink>
            ))}
          </Nav>

          {/* Правый верх — соцсети */}
          <Socials>
            <SocialBtn
              as="a"
              href={linkedinUrl}
              target="_blank"
              rel="noreferrer"
              aria-label="LinkedIn"
              title="LinkedIn"
            >
              <img src="/imgs/in.svg" width={18} height={18} alt="" />
            </SocialBtn>
          </Socials>
        </Top>
          {/* Низ: на десктопе — копирайт слева и ссылки справа; на мобиле скрыт */}
          <BottomRow>
            <CopyDesktop>{`© ${year} Freedom Telecom International. All Rights Reserved`}</CopyDesktop>
            <LegalRowDesktop>
              <LegalLink to="/privacy">Privacy policy</LegalLink>
              <Separator>·</Separator>
              <LegalLink to="/disclaimer">Disclaimer</LegalLink>
            </LegalRowDesktop>
          </BottomRow>

          {/* Низ для мобилы — отдельная строка ссылок */}
          <LegalRowMobile>
            <LegalLink to="/privacy">Privacy policy</LegalLink>
            <LegalLink to="/disclaimer">Disclaimer</LegalLink>
          </LegalRowMobile>
      </Inner>
    </Wrap>
  );
};

export default FooterSection;

/* ================= styles ================= */

const Wrap = styled.footer`
  width: 100%;
  background: #1d2023;
  color: #ffffff;
  padding: 64px 40px;
  @media (max-width: 950px) {
    padding: 32px 40px;
  }
`;

const Inner = styled.div`
  max-width: 1360px;
  margin: 0 auto;
`;

const Top = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 32px;

  @media (max-width: 950px) {
    position: relative;
    display: grid;
    grid-template-columns: 1fr;
    grid-row-gap: 0px;
    grid-template-areas:
      "logo"
      "copy-mobile"
      "nav"
      "legal-mobile";
  }
`;

const LogoRow = styled.div`
  grid-area: logo;
  padding: 8px 0;
`;

const Logo = styled.img`
  display: block;
  height: 32px;
  width: auto;
`;

const Nav = styled.nav`
  grid-area: nav;
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
  margin-top: 4px;
  margin-right: auto;

  @media (max-width: 950px) {
    flex-direction: column;
    gap: 12px;
    margin:32px 0px;
  }
`;

const NavLink = styled.a`
 
  font-weight: 400;
  font-style: Regular;
  font-size: 12px;
  leading-trim: NONE;
  line-height: 16px;
  letter-spacing: 4%;
  vertical-align: middle;
  text-transform: uppercase;

  color: #ffffff;
  text-decoration: none;
  letter-spacing: 0.02em;

  &:hover {
    text-decoration: underline;
  }
`;

/* --- копирайт --- */
const CopyBase = styled.div`
  ${Text12_400 as any};
  color: #acacad;
`;

const CopyDesktop = styled(CopyBase)`
  display: block;
  font-size: 14px;
  @media (max-width: 950px) {
    display: none;
  }
`;

const CopyMobile = styled(CopyBase)`
  grid-area: copy-mobile;
  display: none;
  font-size:14px;
  @media (max-width: 950px) {
    display: block;
    margin-top: 16px;
  }
`;

/* --- низ на десктопе --- */
const BottomRow = styled.div`
  grid-area: bottom;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-top:16px;

  @media (max-width: 950px) {
    display: none; /* на мобиле скрываем: используется мобильный низ */
  }
`;

const LegalRowDesktop = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  font-size:16px;
`;

const Separator = styled.span`
  color: #6a6d78;
  opacity: 0.8;
`;

/* --- низ на мобиле --- */
const LegalRowMobile = styled.div`
  grid-area: legal-mobile;
  display: none;
  font-size:16px;

  @media (max-width: 950px) {
    display: flex;
    gap: 24px;
  }
`;

const LegalLink = styled(Link)`
  ${Text14_400 as any};
  color: #acacad;
  text-decoration: none;
  text-underline-offset: 2px;

  &:hover {
    text-decoration: underline;
    opacity: 0.95;
  }
`;

const Socials = styled.div`
  @media (max-width: 950px) {
    position: absolute;
    right: 0;
    top: 0;
  }
`;

const SocialBtn = styled.button`
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: grid;
  place-items: center;
  cursor: pointer;

  img {
    width: 18px;
    height: 18px;
  }

  &:hover {
    background: rgba(255, 255, 255, 0.08);
  }
  &:active {
    transform: scale(0.98);
  }
`;
