// src/sections/SolutionsSection.tsx
import React, { useEffect, useMemo, useRef, useState } from "react";
import styled, { css } 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;

export default function SolutionsSection({
  items: overrideItems,
  buttonText: overrideButtonText,
}: {
  /** можно пробросить готовый список извне; иначе берём из CMS, иначе — локальный SOLUTIONS */
  items?: SolutionItem[];
  /** можно переопределить текст кнопки; иначе — из CMS, иначе — дефолт */
  buttonText?: string;
}) {
  /* ===== получаем данные из CMS ===== */
  const { data: section, 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 ?? "",
      })),
    [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 rowRef = useRef<HTMLDivElement>(null);
  const firstFrameRef = useRef<HTMLDivElement>(null);

  // вычисленная ширина карточки в пикселях
  const [cardW, setCardW] = useState<number>(MIN_W - 3.33);

  // состояния краёв для дизейбла стрелок
  const [atStart, setAtStart] = useState(true);
  const [atEnd, setAtEnd] = useState(false);

  // шаг прокрутки — по факту DOM: ширина первой карточки + реальный gap
  const getStep = () => {
    const row = rowRef.current;
    const first = firstFrameRef.current;
    const gap =
      row ? parseFloat(getComputedStyle(row).gap || "0") : GAP;
    const w =
      first ? Math.round(first.getBoundingClientRect().width) : Math.round(cardW);
    return w + gap;
  };

  const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n));

  const scrollToIndex = (idx: number) => {
    const el = viewportRef.current;
    if (!el) return;
    const step = getStep();
    const maxLeft = el.scrollWidth - el.clientWidth;
    const left = clamp(idx * step, 0, Math.max(0, maxLeft));
    el.scrollTo({ left, behavior: "smooth" });
    // обновим края после инерции
    window.setTimeout(() => {
      const eps = 2;
      setAtStart(el.scrollLeft <= eps);
      setAtEnd(el.scrollLeft + el.clientWidth >= el.scrollWidth - eps);
    }, 250);
  };

  const getIndex = () => {
    const el = viewportRef.current;
    if (!el) return 0;
    const step = getStep();
    return Math.round(el.scrollLeft / step);
  };

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

    const syncEdges = () => {
      const eps = 2;
      const sl = el.scrollLeft;
      const cw = el.clientWidth;
      const sw = el.scrollWidth;
      setAtStart(sl <= eps);
      setAtEnd(sl + cw >= sw - eps);
    };

    const recompute = () => {
      const w = el.clientWidth;
      const need = 3 * MIN_W + 2 * GAP; // хотим 3 колонки, если помещаются
      if (w >= need) {
        const px = Math.floor((w - 2 * GAP) / 3) - 3.33;
        setCardW(px);
      } else {
        setCardW(MIN_W - 3.33);
      }
      syncEdges();
    };

    recompute();
    const ro = new ResizeObserver(recompute);
    ro.observe(el);

    el.addEventListener("scroll", syncEdges, { passive: true });
    window.addEventListener("orientationchange", recompute);

    return () => {
      ro.disconnect();
      el.removeEventListener("scroll", syncEdges);
      window.removeEventListener("orientationchange", recompute);
    };
  }, []);

  // при изменении количества карточек / ширины карточки — обновим края
  useEffect(() => {
    const el = viewportRef.current;
    if (!el) return;
    const eps = 2;
    setAtStart(el.scrollLeft <= eps);
    setAtEnd(el.scrollLeft + el.clientWidth >= el.scrollWidth - eps);
  }, [usedItems.length, cardW]);

  const animatePrev = () => {
    if (atStart) return;
    scrollToIndex(getIndex() - 1);
  };

  const animateNext = () => {
    if (atEnd) return;
    scrollToIndex(getIndex() + 1);
  };

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

      <Viewport ref={viewportRef}>
        <Row ref={rowRef} $gap={GAP}>
          {usedItems.map((it, i) => (
            <Frame
              key={it.id}
              ref={i === 0 ? firstFrameRef : undefined}
              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>
      </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: 64px 0px 64px;
  @media (max-width: 768px) {
    padding: 48px 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`
  position: relative;
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  padding-left: 10px; /* переносим левый отступ сюда, чтобы он не влиял на вычисление шага */

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

const Row = styled.div<{ $gap: number }>`
  display: flex;
  gap: ${(p) => p.$gap}px;
`;

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;
    }
  }
`;
