// Cases.jsx — case studies with before/after carousel and video grid

const BeforeAfterSlider = ({ beforeSrc, afterSrc }) => {
  const containerRef = React.useRef(null);
  const [position, setPosition] = React.useState(50);
  const dragging = React.useRef(false);

  const calcPos = (clientX) => {
    const rect = containerRef.current.getBoundingClientRect();
    return Math.min(Math.max(((clientX - rect.left) / rect.width) * 100, 0), 100);
  };

  React.useEffect(() => {
    const onMove = (e) => {
      if (!dragging.current) return;
      const clientX = e.touches ? e.touches[0].clientX : e.clientX;
      setPosition(calcPos(clientX));
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove, { passive: true });
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  const startDrag = (clientX) => {
    dragging.current = true;
    setPosition(calcPos(clientX));
  };

  return (
    <div
      ref={containerRef}
      className="ba-slider"
      onMouseDown={(e) => startDrag(e.clientX)}
      onTouchStart={(e) => startDrag(e.touches[0].clientX)}
    >
      <img className="ba-slider__img" src={afterSrc} alt="Після" draggable="false" loading="lazy" />
      <div className="ba-slider__before" style={{ clipPath: `inset(0 ${100 - position}% 0 0)` }}>
        <img className="ba-slider__img" src={beforeSrc} alt="До" draggable="false" loading="lazy" />
      </div>
      <span className="ba-label ba-label--before">ДО</span>
      <span className="ba-label ba-label--after">ПІСЛЯ</span>
      <div className="ba-slider__line" style={{ left: `${position}%` }}>
        <button
          className="ba-slider__handle"
          aria-label="Перетягніть для порівняння"
          onMouseDown={(e) => { e.stopPropagation(); dragging.current = true; }}
          onTouchStart={(e) => { e.stopPropagation(); dragging.current = true; }}
        >
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
            <path d="M7 10H13M7 10L5 7.5M7 10L5 12.5M13 10L15 7.5M13 10L15 12.5"
              stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </div>
  );
};

const BeforeAfterCarousel = ({ pairs }) => {
  const [current, setCurrent] = React.useState(0);
  const total = pairs.length;
  const touchStartX = React.useRef(null);

  const prev = () => setCurrent(c => (c - 1 + total) % total);
  const next = () => setCurrent(c => (c + 1) % total);

  const onTouchStart = (e) => { touchStartX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchStartX.current === null) return;
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    if (Math.abs(dx) > 40) dx < 0 ? next() : prev();
    touchStartX.current = null;
  };

  return (
    <div className="ba-carousel" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
      <BeforeAfterSlider
        key={current}
        beforeSrc={pairs[current].before}
        afterSrc={pairs[current].after}
      />
      <div className="ba-carousel__nav">
        <button className="ba-carousel__btn" onClick={prev} aria-label="Попередній">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M10 3L5 8L10 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div className="ba-carousel__dots">
          {pairs.map((_, i) => (
            <button
              key={i}
              className={`ba-carousel__dot${i === current ? ' ba-carousel__dot--active' : ''}`}
              onClick={() => setCurrent(i)}
              aria-label={`Пара ${i + 1}`}
            />
          ))}
        </div>
        <button className="ba-carousel__btn" onClick={next} aria-label="Наступний">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M6 3L11 8L6 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </div>
  );
};

const VideoCarousel = ({ videos }) => {
  const [current, setCurrent] = React.useState(0);
  const total = videos.length;
  const touchStartX = React.useRef(null);

  const prev = () => setCurrent(c => (c - 1 + total) % total);
  const next = () => setCurrent(c => (c + 1) % total);

  const onTouchStart = (e) => { touchStartX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchStartX.current === null) return;
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    if (Math.abs(dx) > 40) dx < 0 ? next() : prev();
    touchStartX.current = null;
  };

  return (
    <div className="dd-case__video-section">
      <span className="eyebrow">ВІДЕО ДЛЯ ЦЬОГО КЕЙСУ</span>
      <div className="vid-carousel" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
        <video
          key={current}
          className="vid-carousel__item"
          controls
          preload="metadata"
        >
          <source src={videos[current].src} type="video/mp4" />
        </video>
        <div className="ba-carousel__nav">
          <button className="ba-carousel__btn" onClick={prev} aria-label="Попереднє відео">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M10 3L5 8L10 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
          <div className="ba-carousel__dots">
            {videos.map((_, i) => (
              <button
                key={i}
                className={`ba-carousel__dot${i === current ? ' ba-carousel__dot--active' : ''}`}
                onClick={() => setCurrent(i)}
                aria-label={`Відео ${i + 1}`}
              />
            ))}
          </div>
          <button className="ba-carousel__btn" onClick={next} aria-label="Наступне відео">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M6 3L11 8L6 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
};

const StatPill = ({ value, label }) => (
  <div className="dd-stat">
    <div className="dd-stat__v">{value}</div>
    <div className="dd-stat__l">{label}</div>
  </div>
);

const CASES = [
  {
    id: '01',
    title: 'Дієтолог.',
    body: 'Замінити страви на наявних фото на страви з книги, зберігаючи фон і освітлення. Покращити якість, додати атмосферне світло. Анімувати ключові кадри для відеореклами.',
    stats: [
      { value: '300+', label: 'нових відео' },
      { value: '∞',    label: 'постійна співпраця' },
    ],
    quote: 'Дякую за співпрацю. Ціную Ваш час і роботу, а також умови, які пропонуєте.',
    attr: 'Дієтолог', attrSub: 'постійна співпраця',
    beforeAfterPairs: [
      { before: 'assets/case1-before-1.png', after: 'assets/case1-after-1.png' },
      { before: 'assets/case1-before-2.png', after: 'assets/case1-after-2.png' },
      { before: 'assets/case1-before-3.jpeg', after: 'assets/case1-after-3.jpeg' },
    ],
    videos: [
      { src: 'assets/case1-video1.mp4', poster: '' },
      { src: 'assets/case1-video2.mp4', poster: '' },
      { src: 'assets/case1-video3.mp4', poster: '' },
    ],
  },
  {
    id: '02',
    title: 'Пекарня.',
    body: 'Власник пекарні звернувся за рекомендацією попереднього клієнта. Завдання: оновити фото випічки та отримати кадри для книги рецептів тостів.',
    stats: [
      { value: '60+',  label: 'фото для книги' },
      { value: '−70%', label: 'витрат' },
      { value: '3 дні', label: 'час виконання' },
    ],
    quote: 'Так, все супер, дякую за оперативну роботу.',
    attr: 'Власник пекарні', attrSub: null,
    beforeAfterPairs: [
      { before: 'assets/case2-before-1.jpg',  after: 'assets/case2-after-1.jpeg' },
      { before: 'assets/case2-before-2.jpg',  after: 'assets/case2-after-2.jpeg' },
      { before: 'assets/case2-before-3.jpeg', after: 'assets/case2-after-3.jpeg' },
    ],
    videos: [
      { src: 'assets/case2-video1.mp4', poster: '' },
      { src: 'assets/case-video2.mp4',  poster: '' },
      { src: 'assets/case2-video3.mp4', poster: '' },
    ],
  },
];

const Cases = () => (
  <section className="dd-section" id="cases">
    <div className="container-x">
      <h2 className="dd-section__title">
        <span className="h-display">Реальні застосування.</span>
      </h2>
      {CASES.map((c) => (
        <div key={c.id} className="dd-case">
          <div className="dd-case__copy">
            <span className="eyebrow">КЕЙС {c.id}</span>
            <h3 className="h-editorial dd-case__title">{c.title}</h3>
            <p className="p-lg">{c.body}</p>
            <div className="dd-case__stats">
              {c.stats.map((s, i) => <StatPill key={i} value={s.value} label={s.label} />)}
            </div>
            <div className="pullquote">
              {c.quote}
              <div className="dd-case__attr">
                — <span className="gold">{c.attr}</span>{c.attrSub ? `, ${c.attrSub}` : ''}
              </div>
            </div>
          </div>
          <BeforeAfterCarousel pairs={c.beforeAfterPairs} />
          <VideoCarousel videos={c.videos} />
        </div>
      ))}
    </div>
  </section>
);
window.Cases = Cases;
