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

/* ---------- данные ---------- */
type NewsItem = { id: string; title: string; image: string; href?: string };

const NEWS: NewsItem[] = [
  { id: "n1", title: "Launch of Freedom Telecom in Kazakhstan", image: "/imgs/news/1.jpg", href: "#" },
  { id: "n2", title: "Let's build the future of telecom–fintech together", image: "/imgs/news/2.jpg", href: "#" },
  { id: "n3", title: "Integration of fintech services into telecom offerings", image: "/imgs/news/3.jpg", href: "#" },
  { id: "n4", title: "New roaming partnerships announced", image: "/imgs/news/4.jpg", href: "#" },
  { id: "n5", title: "5G backbone expansion update", image: "/imgs/news/5.jpg", href: "#" },
  { id: "n6", title: "SuperApp milestone reached", image: "/imgs/news/6.jpg", href: "#" },
];

const GAP = 24;             // расстояние между карточками
const MIN_W = 275;          // минимальная ширина карточки
const MIN_H = 275;          // минимальная высота карточки

const NewsSection: React.FC<{ items?: NewsItem[]; title?: string }> = ({
  items = NEWS,
  title = "News",
}) => {
  const [visible, setVisible] = useState(3);
  const scrollerRef = useRef<HTMLDivElement>(null);
  const [stretch, setStretch] = useState(false);

  // «Растягивать ли?» — если видимых ≤ 3 и контейнер вмещает их по 275px + гэпы
  useEffect(() => {
    const el = scrollerRef.current;
    if (!el) return;

    const recompute = () => {
      const n = Math.min(visible, 3);
      const need = n * MIN_W + (n - 1) * GAP;     // минимум для n карточек
      setStretch(visible <= 3 && el.clientWidth >= need);
    };

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

  const canLoadMore = visible < items.length;
  const showMore = () => setVisible(v => Math.min(v + 3, items.length));

  return (
    <Section>
      <Header>
        <Text40_700>{title}</Text40_700>
        {canLoadMore && (
          <MoreButton onClick={showMore}>
            <Text18_400 as="span">More</Text18_400>
          </MoreButton>
        )}
      </Header>

      <Scroller ref={scrollerRef}>
        {items.slice(0, visible).map((n) => (
          <Card
            key={n.id}
            $stretch={stretch}
            $cols={Math.min(visible, 3)}
            $gap={GAP}
            as={n.href ? "a" : "div"}
            href={n.href}
          >
            <Bg style={{ backgroundImage: `url(${n.image})` }} />
            <Overlay />
            <Inner>
              <CardText>{n.title}</CardText>
            </Inner>
          </Card>
        ))}
      </Scroller>
    </Section>
  );
};

export default NewsSection;

/* ---------- стили ---------- */

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

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

const MoreButton = styled.button`
  background: transparent;
  border: none;
  padding: 4px 0;
  cursor: pointer;
  color: #6b7280;
  &:hover { text-decoration: underline; }
`;

const Scroller = styled.div`
  display: flex;
  gap: ${GAP}px;
  overflow-x: auto;                 /* если не вмещается — появится скролл */
  padding-bottom: 4px;
  min-height: ${MIN_H}px;
  -webkit-overflow-scrolling: touch;

  scrollbar-width: thin;
  &::-webkit-scrollbar { height: 8px; }
  &::-webkit-scrollbar-thumb { background: #e5e7eb; border-radius: 8px; }
  &::-webkit-scrollbar-track { background: transparent; }
`;

const Card = styled.a<{ $stretch: boolean; $cols: number; $gap: number }>`
  position: relative;
  height: ${MIN_H}px;
  border-radius: 14px;
  overflow: hidden;
  text-decoration: none;
  color: #fff;
  display: block;
  transform: translateZ(0);

  ${({ $stretch, $cols, $gap }) =>
    $stretch
      ? `
    flex: 1 1 calc((100% - ${$gap * ($cols - 1)}px) / ${$cols});
    max-width: calc((100% - ${$gap * ($cols - 1)}px) / ${$cols});
    min-width: ${MIN_W}px;
  `
      : `
    flex: 0 0 ${MIN_W}px;
    max-width: ${MIN_W}px;
  `}

  &:hover { transform: translateY(-2px); transition: transform .15s ease; }
`;

const Bg = styled.div`
  position: absolute;
  inset: 0;
  background-size: cover;
  background-position: center;
`;

const Overlay = styled.div`
  position: absolute;
  inset: 0;
  background: linear-gradient(180deg, rgba(0,0,0,0.15) 20%, rgba(0,0,0,0.55) 100%);
`;

/* ⬇️ новый слой с паддингом 24 */
const Inner = styled.div`
  position: absolute;
  inset: 0;
  padding: 24px;             /* требуемые внутренние отступы */
  display: flex;
  align-items: flex-end;     /* текст у нижнего края */
`;

const CardText = styled(Text18_400)`
  color: #ffffff;
  text-shadow: 0 2px 8px rgba(0,0,0,0.35);
`;
