"use client";

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

const SectorItem = ({ iconSrc, title, desc, isFirst }: { iconSrc: string, title: string, desc: string; isFirst?: boolean }) => (
  <div className={`
    group flex flex-col sm:flex-row items-start 
    gap-[20px] sm:gap-[30px] mb-[20px] pb-[20px] 
    ${isFirst ? "pt-[20px] border-t border-b border-[#FFFFFF]/20" : "border-b border-[#FFFFFF]/20"}
  `}>
    <div 
      className="bg-[#DAE6DC] w-[60px] h-[60px] flex items-center justify-center rounded-xl shrink-0 transition-transform duration-300 ease-in-out hover:scale-x-[-1] group-hover:scale-x-[-1]"
      dangerouslySetInnerHTML={{ __html: iconSrc }}
    />

    <div className='font-outfit'>
      <h5 className="font-semibold text-[20px] text-white pb-[10px]">{title}</h5>
      <h5 className="font-light text-[20px] text-white">{desc}</h5>
    </div>
  </div>
);

interface SectorServeProps {
  title?: string;
  description?: string;
  sectors?: any[];
  backgroundImageMobile?: string;
  backgroundImageDesktop?: string;
  backgroundImageMobileAlt?: string;
  backgroundImageDesktopAlt?: string;
}

const FALLBACK_SECTOR_BG = "/sectorServe_bg_img.png";

const SectorServe: React.FC<SectorServeProps> = ({
  title,
  description,
  sectors,
  backgroundImageMobile,
  backgroundImageDesktop,
  backgroundImageMobileAlt,
  backgroundImageDesktopAlt,
}) => {
  const sectionRef = useRef<HTMLElement>(null);
  const [inView, setInView] = useState(false);
  const headingHtml = (() => {
    const rawTitle = (title || "").trim();
    if (!rawTitle) return "";
    const words = rawTitle.split(/\s+/);
    if (words.length <= 2) return rawTitle;
    return `${words.slice(0, 2).join(" ")} <span class="font-medium">${words.slice(2).join(" ")}</span>`;
  })();

  useEffect(() => {
    const el = sectionRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => setInView(!!entry.isIntersecting),
      { threshold: 0.15, rootMargin: "0px" }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  return (
    <section
      ref={sectionRef}
      className={`relative overflow-hidden rounded-[20px] p-[20px] md:p-[30px] mb-[50px] sm:mb-12 md:mb-14 lg:mb-16 xl:mb-[70px] ${inView ? "sector-serve-in" : ""}`}
    >
      <style dangerouslySetInnerHTML={{
        __html: `
        .sector-serve-step { opacity: 0; }
        .sector-serve-in .sector-serve-step {
          animation: sector-serve-slide-in 0.6s ease-out forwards;
        }
        @keyframes sector-serve-slide-in {
          from { opacity: 0; transform: translateX(-28px); }
          to { opacity: 1; transform: translateX(0); }
        }
      `}} />
      <div className="absolute inset-0 pointer-events-none">
        {(() => {
          const mobile = String(backgroundImageMobile ?? "").trim();
          const desktop = String(backgroundImageDesktop ?? "").trim();
          if (mobile || desktop) {
            return (
              <>
                <div
                  className="absolute inset-0 bg-no-repeat bg-cover bg-center md:hidden"
                  style={{
                    backgroundImage: mobile ? `url('${mobile}')` : desktop ? `url('${desktop}')` : undefined,
                  }}
                  role="img"
                  aria-label={backgroundImageMobileAlt || backgroundImageDesktopAlt || ""}
                />
                <div
                  className="absolute inset-0 hidden bg-no-repeat bg-cover bg-center md:block"
                  style={{
                    backgroundImage: desktop ? `url('${desktop}')` : mobile ? `url('${mobile}')` : undefined,
                  }}
                  role="img"
                  aria-label={backgroundImageDesktopAlt || backgroundImageMobileAlt || ""}
                />
              </>
            );
          }
          return <img src={FALLBACK_SECTOR_BG} className="w-full h-full object-cover" alt="" />;
        })()}
      </div>

      <div className={`relative z-10 max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-[30px] md:gap-12`}>
        <div className="w-full">
          <h2
            className="font-extralight text-white mb-[30px]"
            dangerouslySetInnerHTML={{ __html: headingHtml }}
          />
          <h5 className="font-outfit text-[20px] font-light text-white">
            {description}
          </h5>
        </div>

        <div className="flex flex-col">
          {sectors?.map((sector, index) => (
            <div key={index} className="sector-serve-step" style={{ animationDelay: `${index * 0.08}s` }}>
              <SectorItem
                iconSrc={sector.iconSrc || sector.icon}
                title={sector.title}
                desc={sector.desc || sector.description}
                isFirst={index === 0}
              />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

export default SectorServe;
