"use client";

import React, { useEffect, useRef, useState } from "react";

export function HowItWorksSection() {
  const [activeStep, setActiveStep] = useState<number | null>(1);
  // This section sits below the hero/calculator fold, but the video's
  // `autoPlay` attribute made the browser start fetching its 815KB file
  // immediately on page load anyway — competing for bandwidth with the
  // actually-above-the-fold LCP image (confirmed via Lighthouse: it showed
  // up in the page's total-byte-weight audit alongside the logo/hero
  // requests). Mounting the `<video>` only once this section is actually
  // near the viewport defers that request until it's needed, same as
  // `loading="lazy"` would for an `<img>` (video has no such attribute).
  const [shouldLoadVideo, setShouldLoadVideo] = useState(false);
  const videoWrapperRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const el = videoWrapperRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setShouldLoadVideo(true);
          observer.disconnect();
        }
      },
      { rootMargin: "200px" }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  const toggleStep = (step: number) => {
    setActiveStep((prev) => (prev === step ? null : step));
  };

  const getOrderCpanelUrl = () => {
    const baseUrl = process.env.NEXT_PUBLIC_CPANEL_URL || "https://customerpanel.globalassignmenthelp.com";
    return `${baseUrl}/order?code=EXTRA25`;
  };

  return (
    <section className="sample-and-work">
      <div className="container">
        <p className="home-heading">How it Works ?</p>
        <h2 className="home-subheading">Steps to Get Your Assignment Done by Our Experts</h2>

        <div className="how-it-work">
          {/* Left Side Video Section (Single Continuous Video of All 3 Steps) */}
          <div className="sample-steps" ref={videoWrapperRef}>
            {shouldLoadVideo ? (
              <video
                autoPlay
                muted
                playsInline
                loop
                className="order_process_video"
                style={{ width: "100%", borderRadius: "10px", display: "block" }}
              >
                <source src="/videos/order-video/order-process-assignment.mp4" type="video/mp4" />
              </video>
            ) : (
              // Reserves the video's real aspect ratio (1:1 — confirmed via
              // its own intrinsic dimensions) so mounting it on intersection
              // doesn't shift layout.
              <div style={{ width: "100%", aspectRatio: "1 / 1", borderRadius: "10px" }} aria-hidden="true" />
            )}
          </div>

          {/* Right Side Accordion Steps (Toggle Open/Close On Click) */}
          <div className="order-steps">
            {/* Step 1 */}
            <div
              onClick={() => toggleStep(1)}
              className={`sample-process ${activeStep === 1 ? "current" : ""}`}
              data-id="assignment-1"
              data-full="assignment"
            >
              <div className={`right-head ${activeStep === 1 ? "active" : ""}`}>
                <span className="stepno">01</span>
                <h3>Add Your Details</h3>
              </div>
              <p className="order-detail" style={{ display: activeStep === 1 ? "block" : "none" }}>
                Share the deadline, subject, word count, and requirements in the form to get an instant quote.
              </p>
            </div>

            {/* Step 2 */}
            <div
              onClick={() => toggleStep(2)}
              className={`sample-process ${activeStep === 2 ? "current" : ""}`}
              data-id="common-2"
              data-full="assignment"
            >
              <div className={`right-head ${activeStep === 2 ? "active" : ""}`}>
                <span className="stepno">02</span>
                <h3>Make the Payment</h3>
              </div>
              <p className="order-detail" style={{ display: activeStep === 2 ? "block" : "none" }}>
                Pay securely via card or PayPal. Once done, a writer is assigned, and you get confirmation instantly.
              </p>
            </div>

            {/* Step 3 */}
            <div
              onClick={() => toggleStep(3)}
              className={`sample-process ${activeStep === 3 ? "current" : ""}`}
              data-id="common-3"
              data-full="assignment"
            >
              <div className={`right-head ${activeStep === 3 ? "active" : ""}`}>
                <span className="stepno">03</span>
                <h3>Receive the Delivery</h3>
              </div>
              <p className="order-detail" style={{ display: activeStep === 3 ? "block" : "none" }}>
                Your expert writer will craft and deliver your assignment on time as per your shared details.
              </p>
            </div>

            <a href={getOrderCpanelUrl()} className="btn">
              Order Assignment
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}
