// src/components/Header/index.tsx
import React, { useCallback, useMemo, useState, useEffect } from "react";
import styled from "styled-components";
import logoFallback from "imgs/logo.svg";
import { Button } from "../Button";
import { Text14_500, Text16_400 } from "../Typography";
import { useSingleton, useCollection } from "cms/factory";

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

type CmsSystem = {
  id: string;
  siteTitle?: string | null;
  headerLogo?: { url?: string | null } | null;
};

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

const SYS_SEL = `
  id
  siteTitle
  headerLogo { url }
`;

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

/* ================= utils ================= */

const isHashLink = (href?: string | null) => !!href && href.startsWith("#");
const getHashId = (href?: string | null) => (href && href.startsWith("#") ? href.slice(1) : "");



/* ================= styled (оставь как у тебя) ================= */

const HeaderPlaceholder = styled.div`
  width: 100%;
  height: 56px;
  @media (max-width: 768px) { height: 48px; }
`;

const HeaderBlockOver = styled.header`
  width: 100%;
  position: fixed; top:0; left:0; z-index:1000;
  background:#fff;
  @media (max-width: 768px) { border-bottom:1px solid #E9E9EF; }
`;

const HeaderBlock = styled.div`
  width: 100%; max-width: 1392px; margin: 0 auto;
  height: 56px; display:flex; align-items:center; justify-content:space-between;
  padding: 0 16px;
  @media (max-width: 768px) { height: 48px; }
`;

const Menu = styled.nav`
  display: flex; gap: 32px; justify-content: center; align-items: center;
  @media (max-width: 768px) { display: none; }
`;

const MenuItem = styled.div`
  position: relative; display:flex; align-items:center; min-height:48px; cursor: pointer;
  ${Text16_400 as any}
  &:hover > div[data-submenu="true"] { opacity:1; pointer-events:auto; transform: translateY(0px); }
`;

const Submenu = styled.div`
  position:absolute; top:100%; left:0;
  min-width: 220px; background:#fff; border:1px solid #E9E9EF; border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0,0,0,.06);
  padding: 8px; opacity:0; pointer-events:none; transform: translateY(6px);
  transition: opacity .16s ease, transform .16s ease;
  z-index: 1001;

  a {
    ${Text16_400 as any};
    display:block; color:#1d2023; text-decoration:none; padding: 8px 10px; border-radius: 6px;
    &:hover { background:#F5F8FB; }
  }
`;

const Burger = styled.button<{ open: boolean }>`
  display: none;
  @media (max-width: 768px) { display:flex; }
  width: 24px; height: 18px;
  flex-direction: column; justify-content: space-between;
  cursor:pointer; margin-left:12px;
  background: transparent; border: 0;

  span {
    display:block;
    height:3px; width:100%;
    border-radius:3px;
    background:#1d2023;
    transition: all 0.3s ease;
  }

  span:nth-child(1) {
    transform: ${({ open }) => open ? "rotate(45deg) translate(5px, 5px)" : "none"};
  }
  span:nth-child(2) {
    opacity: ${({ open }) => open ? 0 : 1};
  }
  span:nth-child(3) {
    transform: ${({ open }) => open ? "rotate(-45deg) translate(5px, -5px)" : "none"};
  }
`;


const MobileMenu = styled.div<{ open: boolean }>`
  position: absolute; top: 48px; right: 0; width: 100%;
  background:#fff; box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: ${({ open }) => (open ? "block" : "none")}; padding: 8px 16px;
`;

const MobileItem = styled.div`
  ${Text16_400 as any}; padding: 12px 0;
`;

const MobileChildren = styled.div<{ open?: boolean }>`
  display: ${({ open }) => (open ? "grid" : "none")};
  gap: 8px; padding: 6px 0 8px 12px;
  a { ${Text16_400 as any}; color:#1d2023; text-decoration:none; padding: 6px 0; }
`;

/* ================= component ================= */

function Header() {
  const [open, setOpen] = useState(false);
  const [openedId, setOpenedId] = useState<string | null>(null);

  // CMS
  const { data: system } = useSingleton<CmsSystem>("System", SYS_SEL);

  useEffect(() => {
    if (system?.siteTitle) {
      document.title = system.siteTitle;
    } else {
      document.title = "Privacy Policy";
    }
  }, [system?.siteTitle]);

  // Меню теперь берём из useCollection (NavItem list)
  const { data: navItems } = useCollection<CmsNavItem>("NavItem", NAV_SEL);

  const logoSrc = system?.headerLogo?.url || logoFallback;

  const items = useMemo(() => {
    if (!navItems) return [];
    // фильтрация только enabled и root (parent == null)
    const roots = navItems
      .filter(i => i.enabled !== false && !(i as any).parent) // если parent не пришёл — значит root
      .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]);

  const handleGo = useCallback((href: string) => {
    if (isHashLink(href)) {
      const id = getHashId(href);
      window.location.hash = id; // eslint-safe, без history.pushState
      setOpen(false);
      setOpenedId(null);
    } else {
      window.location.href = href;
    }
  }, []);

  return (
    <>
      <HeaderPlaceholder />
      <HeaderBlockOver>
        <HeaderBlock>
          <img onClick={() => handleGo("/#freedom")} src={logoSrc} style={{ marginRight: "auto", height: "28px", cursor:'pointer' }} alt={system?.siteTitle || "Logo"} />

          {/* Desktop menu */}
          <Menu>
            {items.map(mi => {
              const hasChildren = (mi.children?.length ?? 0) > 0;
              return (
                <MenuItem key={mi.id} onClick={() => handleGo(mi.href)}>
                  <span>{mi.label}</span>
                  {hasChildren && (
                    <Submenu>
                      {mi.children!.map(ch => (
                        <a key={ch.id} href={ch.href} onClick={e => { e.preventDefault(); handleGo(ch.href); }}>
                          {ch.label}
                        </a>
                      ))}
                    </Submenu>
                  )}
                </MenuItem>
              );
            })}
          </Menu>

          <Button
            style={{ marginLeft: "auto" }}
            size="small"
            variant="green"
            className="desktop-only"
            onClick={() => handleGo("#contact")}
          >
            <Text14_500>Contact us</Text14_500>
          </Button>

          {/* Burger */}
          <Burger open={open} onClick={() => setOpen(v => !v)} aria-label="Menu">
            <span /><span /><span />
          </Burger>

          {/* Mobile menu */}
          <MobileMenu open={open}>
            {items.map(mi => {
              const hasChildren = (mi.children?.length ?? 0) > 0;
              const isOpen = openedId === mi.id;
              return (
                <div key={mi.id}>
                  <MobileItem onClick={() => { hasChildren ? setOpenedId(isOpen ? null : mi.id) : handleGo(mi.href); }}>
                    {mi.label}
                  </MobileItem>
                  {hasChildren && (
                    <MobileChildren open={isOpen}>
                      {mi.children!.map(ch => (
                        <a key={ch.id} href={ch.href} onClick={e => { e.preventDefault(); handleGo(ch.href); }}>
                          {ch.label}
                        </a>
                      ))}
                    </MobileChildren>
                  )}
                </div>
              );
            })}
          </MobileMenu>
        </HeaderBlock>
      </HeaderBlockOver>
    </>
  );
}

export default Header;
