import { useEffect, useRef, useState } from 'react';
import { ForTeachingTab } from './Tabs/ForTeachingTab';
import { SimulatorsTab } from './Tabs/SimulatorsTab';
import { IndustrialTab } from './Tabs/IndustrialTab';

export function Products() {
  const ref1 = useRef<HTMLDivElement>(null);
  const ref2 = useRef<HTMLDivElement>(null);
  const ref3 = useRef<HTMLDivElement>(null);

  const [stiked1, setSticked1] = useState(false);
  const [stiked2, setSticked2] = useState(false);

  function handleMouseMove(e: WheelEvent) {
    setSticked1(
      ref2.current!.getBoundingClientRect().top <=
        +window.getComputedStyle(ref2.current!).top.slice(0, -2),
    );
    setSticked2(
      ref3.current!.getBoundingClientRect().top <=
        +window.getComputedStyle(ref3.current!).top.slice(0, -2),
    );
    if (e.deltaY > 0) {
      if (
        ref1.current!.getBoundingClientRect().top ===
          +window.getComputedStyle(ref1.current!).top.slice(0, -2) &&
        ref2.current!.getBoundingClientRect().top !==
          +window.getComputedStyle(ref2.current!).top.slice(0, -2)
      ) {
        window.scrollBy({
          behavior: 'smooth',
          top:
            ref2.current!.getBoundingClientRect().top -
            +window.getComputedStyle(ref2.current!).top.slice(0, -2),
        });
        setSticked1(true);
      }
      if (
        Math.round(
          ref2.current!.getBoundingClientRect().top -
            +window.getComputedStyle(ref2.current!).top.slice(0, -2),
        ) === 0
      ) {
        window.scrollBy({
          top:
            ref3.current!.getBoundingClientRect().top -
            +window.getComputedStyle(ref3.current!).top.slice(0, -2),
        });
        setSticked2(true);
      }
    }
  }

  useEffect(() => {
    window?.addEventListener('wheel', handleMouseMove);

    return () => {
      window?.removeEventListener('wheel', handleMouseMove);
    };
  }, [ref1, ref2, ref3]);

  return (
    <div
      id="products"
      itemScope
      itemType="http://schema.org/Products"
      className="lg:pt-[100px] sm:max-lg:pt-[70px] max-sm:py-14 lg:-mx-10 sm:-mx-6 -mx-4 sm:space-y-[500px] space-y-10 overflow-clip"
    >
      <IndustrialTab ref={ref1} sticked={stiked1} />
      <SimulatorsTab ref={ref2} sticked={stiked2} />
      <ForTeachingTab ref={ref3} />
    </div>
  );
}
