// src/sections/FooterSection.tsx
import React, { useMemo } from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import {
  s_f_Text18_400 as Text18_400,
  s_Text14_400 as Text14_400,
  s_Text12_400 as Text12_400,
} from "../Typography";
import { useSingleton, useCollection } from "cms/factory";
import { DocumentRenderer, DocumentRendererProps } from "@keystone-6/document-renderer";

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

type CmsSystem = {
  id: string;
  footerLogo?: { url?: string | null } | null;
  footerDisclaimer?: { document: { content: any } } | null;
  linedUrl?: string | null;
};

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

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

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

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

const FooterSection: React.FC = () => {
  // CMS
  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 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>
          <Left>
            <LogoRow >
              <Logo
                onClick={() => {
                  window.location.href = "/#freedom";
                }}
                style={{ cursor:'pointer' }}
                src={logoSrc}
                alt="Logo"
              />

            </LogoRow>

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

            {system?.footerDisclaimer && (
              <Description as="div">
                <DocumentRenderer
                  document={
                    system.footerDisclaimer?.document as unknown as DocumentRendererProps["document"]
                  }
                  renderers={{
                    block: {
                      paragraph: ({ children }) => (
                        <p style={{ margin: "0 0 12px" }}>{children}</p>
                      ),
                    },
                    inline: {
                      link: ({ children, href }) => (
                        <a
                          href={href}
                          style={{ color: "#16a34a", textDecoration: "underline" }}
                        >
                          {children}
                        </a>
                      ),
                    },
                  }}
                />
              </Description>
            )}

            <Divider />

            <PrivacyRow>
              <PrivacyLink as={Link} to="/privacy">
                Privacy policy
              </PrivacyLink>
            </PrivacyRow>
          </Left>

          <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>
      </Inner>
    </Wrap>
  );
};

export default FooterSection;

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

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

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

const Top = styled.div`
  position: relative;
`;

const Left = styled.div`
`;

const LogoRow = styled.div`
  margin-bottom: 16px;
  padding:8px 0px;
`;

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

const Nav = styled.nav`
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
  margin-bottom: 16px;

  @media (max-width: 520px) {
    flex-direction: column;
    gap: 12px;
  }
`;

const NavLink = styled.a`
  ${Text12_400 as any};
  color: #ffffff;
  text-decoration: none;
  letter-spacing: 0.02em;

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

const Description = styled(Text14_400)`
  color: #acacad;
  text-align: left;
`;

const Divider = styled.hr`
  border: 0;
  border-top: 1px solid #414141;
  margin: 16px 0;
`;

const PrivacyRow = styled.div`
  display: flex;
`;

const PrivacyLink = styled.button`
  ${Text14_400 as any};
  color: #acacad;
  background: transparent;
  border: none;
  padding: 0;
  cursor: pointer;
  text-decoration: underline;
  text-underline-offset: 2px;

  &:hover {
    opacity: 0.9;
  }
`;

const Socials = styled.div`
  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);
  }
`;
