// src/sections/LeadershipSection.tsx
import React, { useEffect, useState } from "react";
import styled from "styled-components";
import {
  s_Text40_700 as Text40_700,
  s_Text24_700 as Text24_700,
  s_f_Text18_400 as Text18_400,
} from "../Typography";

type Leader = {
  id: string;
  name: string;
  role: string;
  photo: string;           // 124×124 на карточке
  photoLarge?: string;     // 254×254 в попапе (если не указан — берём photo)
  description: string[];   // абзацы в попапе
};

// Пример данных — пути к картинкам подставь свои
const TEAM: Leader[] = [
  {
    id: "hummer",
    name: "Johannes Hummer",
    role: "CEO",
    photo: "/imgs/team/johannes.jpg",
    photoLarge: "/imgs/team/johannes_lg.jpg",
    description: [
      "25+ years of international leadership in the ICT industry, including launching new telecom operators and leading regional strategy.",
      "Professor and Lecturer at Central European University and Hult International Business School.",
      "PhD in Business Administration, CEU and Executive MBA in Organizational Leadership, Hult International Business School.",
    ],
  },
  {
    id: "turlov",
    name: "Timur Turlov",
    role: "Board Member, CEO of FRHC",
    photo: "/imgs/team/timur.jpg",
    photoLarge: "/imgs/team/timur_lg.jpg",
    description: [
      "16+ years of experience in the international securities industry, including founding and scaling Freedom Holding Corp. across 22 countries.",
      "Led FRHC’s IPO on Nasdaq in 2019—the first-ever listing of a CIS-based brokerage firm — followed by consistent period of growth and market expansion.",
      "Holds a Bachelor of Science in Economics and Management from Tselinovsky Russian State Technical University.",
    ],
  },
  {
    id: "vogeleer",
    name: "Philippe Vogeleer",
    role: "Board Chair",
    photo: "/imgs/team/philippe.jpg",
    description: [ "Short bio or highlight line goes here." ],
  },
  {
    id: "williams",
    name: "Amber Williams",
    role: "Board Member",
    photo: "/imgs/team/amber.jpg",
    description: [ "Short bio or highlight line goes here." ],
  },
  {
    id: "ler",
    name: "Evgeniy Ler",
    role: "Board Member, CFO of FRHC",
    photo: "/imgs/team/ler.jpg",
    description: [ "Short bio or highlight line goes here." ],
  },
  {
    id: "kerr",
    name: "Jason Kerr",
    role: "Board Member, CLO of FRHC",
    photo: "/imgs/team/kerr.jpg",
    description: [ "Short bio or highlight line goes here." ],
  },
  {
    id: "akhmetov",
    name: "Kairat Akhmetov",
    role: "CEO of Freedom Telekom Kazakhstan",
    photo: "/imgs/team/akhmetov.jpg",
    description: [ "Short bio or highlight line goes here." ],
  },
];

const CLOSE_ICON = "/imgs/close.svg"; // 32×32 внутри кнопки 56×56

const LeadershipSection: React.FC<{ items?: Leader[]; title?: string }> = ({
  items = TEAM,
  title = "Leadership",
}) => {
  const [open, setOpen] = useState<Leader | null>(null);

  // закрытие по Esc + запрет прокрутки под модалкой
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(null);
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = open ? "hidden" : "";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);

  return (
    <Section>
      <Header>
        <Title>{title}</Title>
      </Header>

      <Grid>
        {items.map((p) => (
          <Card key={p.id} onClick={() => setOpen(p)} role="button" tabIndex={0} onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && setOpen(p)}>
            <Portrait src={p.photo} alt={p.name} width={124} height={124} />
            <Name as="h3">{p.name}</Name>
            <Role>{p.role}</Role>
          </Card>
        ))}
      </Grid>

      {open && (
        <Modal onClick={() => setOpen(null)}>
          <Dialog role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
            <CloseBtn aria-label="Close" onClick={() => setOpen(null)}>
              <img src={CLOSE_ICON} alt="" width={32} height={32} />
            </CloseBtn>

            <PopupHeader>
              <PopupName>{open.name}</PopupName>
              <PopupRole>{open.role}</PopupRole>
            </PopupHeader>

            <PopupBody>
              <PopupPortrait
                src={open.photoLarge || open.photo}
                alt={open.name}
                width={254}
                height={254}
              />
              <Desc>
                {open.description.map((para, i) => (
                  <p key={i}>{para}</p>
                ))}
              </Desc>
            </PopupBody>
          </Dialog>
        </Modal>
      )}
    </Section>
  );
};

export default LeadershipSection;

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

const Section = styled.section`
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 10px 64px;
`;

const Header = styled.div`
  display: flex;
  justify-content: center;
  margin-bottom: 32px;
`;

const Title = styled(Text40_700)`
  /* если подключен GT America LCG — заиспользуется */
  font-family: "GT America LCG", system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
  text-align: center;
`;

const Grid = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 32px;                 /* расстояние между карточками */
  justify-content: center;   /* центрирует и полные, и неполные строки */
`;

const Card = styled.button`
  /* Десктоп: фиксированная карточка, чтобы красиво центровалась последняя строка */
  flex: 0 0 240px;           /* ширина карточки 240px */
  max-width: 240px;

  background: transparent;
  border: none;
  padding: 0;
  text-align: center;
  cursor: pointer;

  display: flex;
  flex-direction: column;
  align-items: center;

  &:focus-visible { outline: 2px solid #16a34a; outline-offset: 4px; }

  /* Мобилка: две колонки на процентах с учётом gap */
  @media (max-width: 720px) {
    flex: 0 1 calc((100% - 32px) / 2); /* 2 колонки с 32px зазором */
    max-width: calc((100% - 32px) / 2);
  }
`;


const Portrait = styled.img`
  width: 124px;
  height: 124px;
  border-radius: 12px;
  object-fit: cover;
  background-color:#333;
`;

const Name = styled(Text24_700)`
  margin-top: 32px;       /* отступ от фото до ФИО — 32 */
  color: #1d2023;
`;

const Role = styled(Text18_400)`
  color: #5b6066;
  margin-top: 6px;
`;

/* ---------- modal ---------- */

const Modal = styled.div`
  position: fixed;
  inset: 0;
  background: rgba(29, 32, 35, 0.45);
  display: grid;
  place-items: center;
  padding: 16px;
  z-index: 1000;
`;

const Dialog = styled.div`
  position: relative;
  background: #ffffff;
  border-radius: 16px;     /* радиус попапа 16 */
  width: min(720px, 96vw);
  max-height: 90vh;
  padding: 24px;           /* внутренний отступ 24 */
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
  display: flex;
  flex-direction: column;
`;

const CloseBtn = styled.button`
  position: absolute;
  right: 12px;
  top: 12px;
  width: 56px;
  height: 56px;            /* размер кнопки 56×56 */
  border-radius: 50%;
  background: #f6f6f6;     /* фон кнопки закрытия */
  border: none;
  display: grid;
  place-items: center;
  cursor: pointer;

  img { width: 32px; height: 32px; } /* иконка 32×32 */
`;

const PopupHeader = styled.div`
  margin-right: 72px; /* чтобы кнопка закрытия не перекрывала заголовок */
`;

const PopupName = styled(Text40_700)`
  color: #1d2023;
`;

const PopupRole = styled(Text18_400)`
  color: #5b6066;
  margin-top: 6px;
`;

const PopupBody = styled.div`
  display: grid;
  grid-template-columns: 254px 1fr;
  gap: 24px;
  margin-top: 24px;

  @media (max-width: 700px) {
    grid-template-columns: 1fr;
    justify-items: center;
  }
`;

const PopupPortrait = styled.img`
  width: 254px;
  height: 254px;          /* размер в попапе 254×254 */
  border-radius: 12px;
  object-fit: cover;
`;

const Desc = styled.div`
  ${Text18_400 as any};
  color: #1d2023;
  overflow: auto;
  max-height: calc(90vh - 24px - 56px - 24px - 254px); /* чтобы текст прокручивался при избытке */

  p { margin: 0 0 12px; }
`;
