import { MiniTitle } from '../../ui/MiniTitle';
import { AppearanceText } from '../../ui/AppearanceText';
import { motion, useInView, useMotionValue, useSpring } from 'framer-motion';
import { useEffect, useRef } from 'react';
import { useWindowWidth } from '../../hooks/useWindowWidth';

export function Effeciency() {
  return (
    <div className="lg:py-[70px] py-14">
      <div className="sm:grid lg:grid-cols-12 sm:grid-cols-8 max-sm:space-y-6 gap-x-4 gap-y-8 pt-5">
        <MiniTitle
          text={'экономическая эффективность'}
          className="col-span-3"
        />
        <div className="grid lg:grid-cols-3 sm:grid-cols-2 sm:max-lg:grid-rows-[320px_320px] lg:-mx-10 sm:-mx-6 -mx-4 row-start-2 col-span-full">
          <Figure
            percents={50}
            type="charts"
            title={'сокращение бюджета на обучение сотрудников на'}
          />
          <Figure
            percents={30}
            type="diagram"
            title={'сокращение времени обучения сотрудников на'}
          />
          <Figure
            percents={90}
            type="pizza"
            title={'готовность к опасным ситуациям выше на'}
          />
        </div>
        <AppearanceText
          className="lg:col-span-6 col-span-full row-start-3"
          splits={[
            'В тренажере человек ',
            'принимает решения ',
            'так же, ',
            'как в реальном мире, ',
            'активируя ',
            'те же нейронные ',
            'цепочки в мозгу. ',
            'Это позволяет ',
            'добиться ',
            'реальной ',
            'производительности ',
            'в работе. ',
          ]}
        />
      </div>
    </div>
  );
}

function Figure({
  title,
  percents,
  type,
}: {
  percents: number;
  title: string;
  type: 'charts' | 'diagram' | 'pizza';
}) {
  const width = useWindowWidth();

  const root = useRef<HTMLDivElement>(null);
  const figureRef = useRef<HTMLSpanElement>(null);

  const motionValue = useMotionValue<number>(0);
  const springValue = useSpring(motionValue, {
    damping: 100,
    stiffness: 100,
  });
  const isInView = useInView(root, { once: true, margin: '-200px' });

  useEffect(() => {
    if (isInView) {
      motionValue.set(percents);
    }
  }, [motionValue, isInView, percents]);

  useEffect(() => {
    springValue.on('change', prev => {
      if (figureRef.current) {
        figureRef.current.textContent = prev.toFixed(0);
      }
    });
  }, [springValue]);

  return (
    <motion.div
      ref={root}
      initial={{
        background: `bottom right / 45% url(/images/efficiency/${type}.png) no-repeat, bottom right / 0% url(/images/efficiency/efficiency_backlight.svg) no-repeat`,
      }}
      whileHover={
        width >= 1024
          ? {
              backgroundSize: '45%,100%',
              transition: { duration: 0.125 },
            }
          : {}
      }
      className="flex lg:px-10 px-6 w-full pt-6 bg-no-repeat min-h-[240px] max-sm:border-t max-sm:last:border-b lg:aspect-[532.67/360] relative lg:border-y sm:max-lg:border-t sm:max-lg:last:border-b lg:border-r sm:first:border-r last:border-r-0 border-[#3D425C] sm:max-lg:last:col-span-2 sm:max-lg:row-start-1 sm:max-lg:last:row-start-2"
    >
      <div className="flex flex-col justify-between pb-6 max-sm:max-w-[50vw]">
        <h3 className="lg:font-medium text-2xl 2xl:max-w-[70%] leading-[120%]">
          {title}
        </h3>
        <h1 className="font-medium flex lg:items-center items-end md:text-[clamp(64px,64px+(100vw-768px)/832*32,96px)] md:leading-[clamp(57.6px,57.6px+(100vw-768px)/832*28.8,86.4px)] text-[64px] leading-[57.6px]">
          <span ref={figureRef}>{percents}</span>
          <span className="md:text-[clamp(32px,32px+(100vw-768px)/832*32,64px)] md:leading-[clamp(32px,32px+(100vw-768px)/832*25.6,57.6px)] text-[32px] leading-8">
            %
          </span>
        </h1>
      </div>
    </motion.div>
  );
}
