"use client";

import { useEffect, useRef, useState } from "react";
import TeamStickyImage from "@/components/single-team/TeamStickyImage";
import TeamProfileIntro from "@/components/single-team/TeamProfileIntro";
import TeamContactInfo from "@/components/single-team/TeamContactInfo";
import TeamSkillsSection from "@/components/single-team/TeamSkillsSection";

const TeamDetailSection = () => {
  const sectionRef = useRef<HTMLElement | null>(null);
  const stickyImageRef = useRef<HTMLDivElement | null>(null);
  const [stickyClass, setStickyClass] = useState("");

  useEffect(() => {
    const updateStickyClass = () => {
      const sectionEl = sectionRef.current;
      const stickyEl = stickyImageRef.current;

      if (!sectionEl || !stickyEl) return;

      const sectionTop = sectionEl.getBoundingClientRect().top + window.scrollY;
      const sectionHeight = sectionEl.offsetHeight;
      const contentHeight = stickyEl.offsetHeight;
      const scrollY = window.scrollY;
      const start = sectionTop - 120;
      const end = sectionTop + sectionHeight - contentHeight - 120;

      if (scrollY >= start && scrollY <= end) {
        setStickyClass("is-fixed");
      } else if (scrollY > end) {
        setStickyClass("is-absolute");
      } else {
        setStickyClass("");
      }
    };

    updateStickyClass();
    window.addEventListener("scroll", updateStickyClass, { passive: true });
    window.addEventListener("resize", updateStickyClass);

    return () => {
      window.removeEventListener("scroll", updateStickyClass);
      window.removeEventListener("resize", updateStickyClass);
    };
  }, []);

  return (
    <section ref={sectionRef} className="team-detail">
      <div className="carousel-container">
        <div className="row">
          <div className="col-lg-5">
            <TeamStickyImage stickyClass={stickyClass} imageRef={stickyImageRef} />
          </div>
          <div className="col-lg-7">
            <div className="team-info">
              <TeamProfileIntro />
              <TeamContactInfo />
              <TeamSkillsSection />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default TeamDetailSection;
