// src/sections/SolutionsSection.tsx
import React, { useEffect, useMemo, useRef, useState } from "react";
import styled, { css, keyframes } from "styled-components";
import {
  s_Text40_700 as Text40_700,
  s_Text24_700 as Title18_400,
  s_f_Text18_400 as Text18_400,
} from "../Typography";
import { Button } from "../Button";
import arrowRight from "imgs/arrow_right.svg";
import { useSingleton } from "cms/factory";

/* ===== локальный тип для отображения ===== */
type SolutionItem = {
  id: string;
  title: string;
  text: string;
  href?: string;
  image: string;
};

/* ===== фолбэк-данные, если CMS пуст/не доступен ===== */
const SOLUTIONS: SolutionItem[] = [
  {
    id: "telecom",
    title: "Telecom",
    text:
      "Partnerships, JVs and M&A with Telecom players around the world. Standalone operation in Kazakhstan",
    href: "#",
    image: "/imgs/sol_telecom.jpg",
  },
  {
    id: "brokerage",
    title: "Brokerage",
    text: "Retail brokerage, investment banking, global market access",
    href: "#",
    image: "/imgs/sol_brokerage.jpg",
  },
  {
    id: "banking",
    title: "Banking",
    text:
      "Traditional and Digital banking powered by Freedom SuperApp, license in Kazakhstan and Tajikistan",
    href: "#",
    image: "/imgs/sol_banking.jpg",
  },
  {
    id: "insurance",
    title: "Insurance",
    text:
      "Coverage in all categories of life and non-life insurance, 1st digital auto insurance in Kazakhstan",
    href: "#",
    image: "/imgs/sol_insurance.jpg",
  },
  {
    id: "lifestyle",
    title: "Lifestyle services",
    text:
      "Popular digital platforms for event ticketing, e-grocery services, and travel bookings",
    href: "#",
    image: "/imgs/sol_lifestyle.jpg",
  },
];

/* ===== GraphQL selection под нашу фабрику ===== */
type CmsSolutionItem = {
  id: string;
  title: string;
  text?: string | null;
  href?: string | null;
  image?: { url?: string | null } | null;
  order?: number | null;
};
type CmsSolutionsSection = {
  id: string;
  title?: string | null;
  buttonText?: string | null;
  buttonHref?: string | null;
  items: CmsSolutionItem[];
};

const SELECTION = `
  id
  title
  buttonText
  buttonHref
  items(orderBy: { order: asc }) {
    id
    title
    text
    href
    order
    image { url }
  }
`;


const GAP = 24;
const MIN_W = 275;
const DESK_H = 295;
const MOB_H = 266;
const DURATION = 260; // ms

export default function SolutionsSection({
  items: overrideItems,
  buttonText: overrideButtonText,
}: {
  /** можно пробросить готовый список извне; иначе берём из CMS, иначе — локальный SOLUTIONS */
  items?: SolutionItem[];
  /** можно переопределить текст кнопки; иначе — из CMS, иначе — дефолт */
  buttonText?: string;
}) {
  /* ===== получаем данные из CMS ===== */
  const { data: section, loading, error } = useSingleton<CmsSolutionsSection>(
    "SolutionsSection",
    SELECTION
  );

  const cmsItems: SolutionItem[] = useMemo(
    () =>
      (section?.items ?? []).map((it) => ({
        id: it.id,
        title: it.title,
        text: it.text ?? "",
        href: it.href ?? undefined,
        image: it.image?.url ?? "", // у тебя /images проксируются — отдаст абсолютный путь
      })),
    [section]
  );

  // что показываем в итоге
  const usedItems: SolutionItem[] =
    overrideItems && overrideItems.length > 0
      ? overrideItems
      : cmsItems.length > 0
      ? cmsItems
      : SOLUTIONS;

  const usedButtonText =
    overrideButtonText ?? section?.buttonText ?? "Partner with us";

  const buttonHref = section?.buttonHref ?? "#";

  const viewportRef = useRef<HTMLDivElement>(null);

  const VISIBLE = Math.min(3, usedItems.length);

  // текущая левая граница «окна»
  const [start, setStart] = useState(0);
  // вычисленная ширина карточки в пикселях
  const [cardW, setCardW] = useState<number>(MIN_W - 3.33);
  // показываем ли горизонтальный скролл (если 3×MIN_W + 2×GAP не влезают)
  const [scroll, setScroll] = useState(false);

  // анимация
  const [animating, setAnimating] = useState(false);
  const [mode, setMode] = useState<"next" | "prev">("next");
  const [overlayItems, setOverlayItems] = useState<SolutionItem[]>([]);

  // пересчёт cardW и scroll (фиксированные пиксели)
  useEffect(() => {
    const el = viewportRef.current;
    if (!el) return;

    const recompute = () => {
      const w = el.clientWidth;
      const need = 3 * MIN_W + 2 * GAP;
      if (w >= need) {
        // тянем три колонки на всю ширину контейнера, но в ПИКСЕЛЯХ
        const px = Math.floor((w - 2 * GAP) / 3) - 3.33;
        setCardW(px);
        setScroll(false);
      } else {
        setCardW(MIN_W - 3.33);
        setScroll(true);
      }
    };

    recompute();
    const ro = new ResizeObserver(recompute);
    ro.observe(el);
    window.addEventListener("orientationchange", recompute);
    return () => {
      ro.disconnect();
      window.removeEventListener("orientationchange", recompute);
    };
  }, []);

  // держим start в допустимых пределах при изменении количества карточек
  useEffect(() => {
    const maxStart = Math.max(0, usedItems.length - VISIBLE);
    if (start > maxStart) setStart(maxStart);
  }, [usedItems.length, VISIBLE, start]);

  const atStart = start === 0;
  const atEnd = start + VISIBLE >= usedItems.length;

  const windowItems = usedItems.slice(start, start + VISIBLE);

  const animateNext = () => {
    if (animating || atEnd || VISIBLE < 3) return;
    setMode("next");
    setAnimating(true);
    // порядок 4-х: [L, M1, M2, E]
    const entering = usedItems[start + VISIBLE]; // новая справа
    setOverlayItems([windowItems[0], windowItems[1], windowItems[2], entering]);
    window.setTimeout(() => {
      setStart((s) => s + 1);
      setAnimating(false);
      setOverlayItems([]);
    }, DURATION);
  };

  const animatePrev = () => {
    if (animating || atStart || VISIBLE < 3) return;
    setMode("prev");
    setAnimating(true);
    // порядок 4-х: [E, M1, M2, L]
    const entering = usedItems[start - 1]; // новая слева
    setOverlayItems([entering, windowItems[0], windowItems[1], windowItems[2]]);
    window.setTimeout(() => {
      setStart((s) => s - 1);
      setAnimating(false);
      setOverlayItems([]);
    }, DURATION);
  };

  return (
    <Section id="solutions">
      <Header>
        <Text40_700>{section?.title || "Solutions"}</Text40_700>
        <Controls>
          <ArrowBtn
            aria-label="Prev"
            disabled={atStart || animating}
            onClick={animatePrev}
          >
            <ArrowIcon $left src={arrowRight} alt="" />
          </ArrowBtn>
          <ArrowBtn
            aria-label="Next"
            disabled={atEnd || animating}
            onClick={animateNext}
          >
            <ArrowIcon src={arrowRight} alt="" />
          </ArrowBtn>
        </Controls>
      </Header>

      <Viewport ref={viewportRef} $scroll={scroll}>
        {/* базовый ряд из 3 карточек фиксированной ширины в пикселях */}
        <Row
          $gap={GAP}
          $hidden={animating}
          style={!scroll ? undefined : { width: `${3 * MIN_W + 2 * GAP}px` }}
        >
          {windowItems.map((it) => (
            <Frame key={it.id} style={{ width: `${cardW}px` }}>
              <CardStatic
                $img={it.image}
                $deskH={DESK_H}
                $mobH={MOB_H}
                style={{ width: `${cardW}px` }}
              >
                <Overlay />
                <CardBody>
                  <CardTitle as="h3">{it.title}</CardTitle>
                  <CardText as="p">{it.text}</CardText>
                  {it.href && (
                    <CardLink href={it.href}>
                      <Text18_400
                        as="span"
                        style={{ textDecoration: "underline", color:'#fff' }}
                      >
                        Learn more
                      </Text18_400>
                    </CardLink>
                  )}
                </CardBody>
              </CardStatic>
            </Frame>
          ))}
        </Row>

        {/* оверлей-анимация на 4 фреймах, ширины — строго в пикселях */}
        {animating && overlayItems.length === 4 && (
          <AnimOverlay
            $gap={GAP}
            $mode={mode}
            style={
              {
                width: `${(scroll ? MIN_W : cardW) * 3 + GAP * 2}px`,
                ["--w" as any]: `${scroll ? MIN_W : cardW}px`,
              } as React.CSSProperties
            }
          >
            {overlayItems.map((it, idx) => (
              <AnimFrame key={`${it.id}-${idx}`}>
                <CardStatic
                  $img={it.image}
                  $deskH={DESK_H}
                  $mobH={MOB_H}
                  style={{ width: `${scroll ? MIN_W : cardW}px` }}
                >
                  <Overlay />
                  <CardBody>
                    <CardTitle as="h3">{it.title}</CardTitle>
                    <CardText as="p">{it.text}</CardText>
                  </CardBody>
                </CardStatic>
              </AnimFrame>
            ))}
          </AnimOverlay>
        )}
      </Viewport>

      <ActionRow>
        <Button size="large" variant="green" as="a" href={buttonHref}>
          {usedButtonText}
        </Button>
      </ActionRow>

      {/* (необязательно) можно вывести ошибку CMS, но не ломать фолбэк */}
      {error ? (
        <div style={{ color: "#ffb4b4", fontSize: 12, paddingLeft: 10 }}>
          Failed to load CMS: {String(error)}
        </div>
      ) : null}
    </Section>
  );
}

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

const Section = styled.section`
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 0px 64px;
  @media (max-width: 768px) {
    padding: 0 0px 48px;
  }
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding-left: 10px;
`;

const Controls = styled.div`
  display: flex;
  gap: 8px;
`;

const ArrowBtn = styled.button`
  width: 48px;
  height: 48px;
  border: none;
  background: transparent;
  display: grid;
  place-items: center;
  border-radius: 50%;
  cursor: pointer;
  transition: transform 0.15s ease, opacity 0.2s ease;

  &:hover {
    transform: translateY(-1px);
  }
  &:active {
    transform: scale(0.98);
  }
  &:disabled {
    opacity: 0.35;
    pointer-events: none;
  }
`;

const ArrowIcon = styled.img<{ $left?: boolean }>`
  width: 10px;
  height: 20px;
  object-fit: contain;
  ${(p) => p.$left && css`
    transform: rotate(180deg);
  `}
`;

const Viewport = styled.div<{ $scroll: boolean }>`
  position: relative;
  width: 100%;
  overflow-x: ${(p) => (p.$scroll ? "auto" : "hidden")};
  -webkit-overflow-scrolling: touch;

  /* скрываем скроллбар */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
  &::-webkit-scrollbar {
    display: none;
  }
`;

const Row = styled.div<{ $gap: number; $hidden?: boolean }>`
  display: flex;
  gap: ${(p) => p.$gap}px;
  visibility: ${(p) => (p.$hidden ? "hidden" : "visible")};
  margin-left:10px;
`;

const Frame = styled.div`
  flex: 0 0 auto;
  overflow-x: hidden;
  border-radius: 16px;
`;

const CardStatic = styled.article<{ $img: string; $deskH: number; $mobH: number }>`
  position: relative;
  height: ${(p) => p.$deskH}px;
  border-radius: 16px;
  overflow: hidden;
  background: #000;
  color: #fff;

  @media (max-width: 768px) {
    height: ${(p) => p.$mobH}px;
  }

  &::before {
    content: "";
    position: absolute;
    inset: 0;
    background-image: url(${(p) => p.$img});
    background-size: cover;
    background-position: center;
    filter: brightness(0.8);
  }
`;

const Overlay = styled.div`
  position: absolute;
  inset: 0;
  background: radial-gradient(
    120% 120% at 0% 100%,
    rgba(0, 0, 0, 0.55) 0%,
    rgba(0, 0, 0, 0.25) 60%,
    rgba(0, 0, 0, 0.15) 100%
  );
  pointer-events: none;
`;

const CardBody = styled.div`
  position: absolute;
  inset: 0;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const CardTitle = styled(Title18_400)`
  color: #fff;
`;
const CardText = styled(Text18_400)`
  color: #fff;
  opacity: 0.95;
`;

const CardLink = styled.a`
  margin-top: auto;
  color: #fff;
  text-decoration: none;
  span {
    text-decoration: underline;
  }
`;

const ActionRow = styled.div`
  margin-top: 24px;
  display: flex;
  padding-left: 10px;
  @media (max-width: 768px) {
    a{
      width:100%;
      margin-right:10px;
    }
  }
`;

const leavePx = keyframes`
  0%   { width: var(--w); }
  50%  { width: calc(var(--w) * 0.5); }
  100% { width: 0px; }
`;
const enterPx = keyframes`
  0%   { width: 0px; }
  50%  { width: calc(var(--w) * 0.5); }
  100% { width: var(--w); }
`;

const AnimOverlay = styled.div<{ $gap: number; $mode: "next" | "prev" }>`
  position: absolute;
  inset: 0;
  pointer-events: none;

  display: flex;
  gap: ${(p) => p.$gap}px;

  & > div {
    flex: 0 0 auto;
    width: var(--w);
    overflow-x: hidden;
    border-radius: 16px;
  }

  ${(p) =>
    p.$mode === "next" &&
    css`
      & > div:nth-child(1) {
        animation: ${leavePx} ${DURATION}ms ease forwards;
      }
      & > div:nth-child(4) {
        animation: ${enterPx} ${DURATION}ms ease forwards;
        width: 0;
      }
    `}

  ${(p) =>
    p.$mode === "prev" &&
    css`
      & > div:nth-child(1) {
        animation: ${enterPx} ${DURATION}ms ease forwards;
        width: 0;
      }
      & > div:nth-child(4) {
        animation: ${leavePx} ${DURATION}ms ease forwards;
      }
    `}
`;

const AnimFrame = ({ children }: { children: React.ReactNode }) => (
  <div>
    <div style={{ width: "var(--w)" }}>{children}</div>
  </div>
);
