"use client";

import { useState, useEffect, useRef } from "react";
import { helpContactData } from "@/data/help/helpContactData";
import Image from "next/image";
import Link from "next/link";
import dynamic from "next/dynamic";

const FaqVideoModal = dynamic(() => import("./FaqVideoModal"), { ssr: false });

export default function HelpContact() {
  const { title, description, cta, video } = helpContactData;
  const [isOpen, setIsOpen] = useState(false);
  const [stickyClass, setStickyClass] = useState("");
  const contentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleScroll = () => {
      const element = contentRef.current;
      if (!element) return;

      const parent = element.parentElement;
      if (!parent) return;

      const parentRect = parent.getBoundingClientRect();
      const elementHeight = element.offsetHeight;
      const topOffset = 120; // Adjust this if you have a fixed header height

      // Calculate the exact width the element should be to avoid shaking
      const parentStyle = window.getComputedStyle(parent);
      const paddingLeft = parseFloat(parentStyle.paddingLeft);
      const paddingRight = parseFloat(parentStyle.paddingRight);
      const correctWidth = parent.clientWidth - paddingLeft - paddingRight;

      // Apply the width explicitly
      element.style.width = `${correctWidth}px`;

      if (parentRect.top <= topOffset) {
        if (parentRect.bottom <= elementHeight + topOffset) {
          setStickyClass("is-absolute");
        } else {
          setStickyClass("is-fixed");
        }
      } else {
        setStickyClass("");
        // When not sticky, we could optionally remove the explicit width so it's responsive again
        // But since we calculate on scroll, keeping it is also fine. Let's let it be responsive:
        element.style.width = "";
      }
    };

    window.addEventListener("scroll", handleScroll);
    // Initial check on mount
    handleScroll();

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsOpen(false);
      }
    };

    window.addEventListener("keydown", handleEscape);
    document.body.style.overflow = "hidden";

    return () => {
      window.removeEventListener("keydown", handleEscape);
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  return (
    <div
      ref={contentRef}
      className={`faq-content ${stickyClass}`.trim()}
    >
      <div
        data-aos="fade-right"
        data-aos-duration={900}
        data-aos-delay={300}
      >
        <h1 className="title">{title}</h1>
        <p>{description}</p>
        <Link href={cta.href} className="btn-style1">
          {cta.label}
          <span>
            <Image src={cta.iconSrc} alt="Arrow Icon" width={14} height={14} />
          </span>
        </Link>
        <div className="video-box">
          <Image
            src={video.thumbnailSrc}
            alt="Video Thumbnail"
            width={500}
            height={300}
            style={{ width: "auto", height: "auto" }}
          />
          <button
            className="video-trigger"
            onClick={() => setIsOpen(true)}
            type="button"
            aria-label="Play Video"
          >
            {video.triggerIcon}
          </button>
        </div>

        <FaqVideoModal
          isOpen={isOpen}
          onClose={() => setIsOpen(false)}
          videoUrl={video.videoUrl}
          title={title}
        />
      </div>
    </div>
  );
}
