import React from "react";
import Link from "next/link";
import Image from "next/image";
import { BaseContent } from "@/types/common.type";

export default function Industries({ data }: { data: BaseContent | undefined }) {
  if (!data) return null;

  
  const extractHref = (htmlString: string): string => {
    // Try to match href in an <a> tag
    const hrefMatch = htmlString.match(/href\s*=\s*["']([^"']+)["']/i);
    if (hrefMatch && hrefMatch[1]) {
      return hrefMatch[1];
    }

    // Fallback: match plain URL inside the text (like in <p>...</p>)
    const urlMatch = htmlString.match(/https?:\/\/[^\s<]+/i);
    return urlMatch ? urlMatch[0] : "#";
  };

  return (
    <section className="container px-4  justify-center items-center gap-5 mb-12 sm:mb-[120px]">
      <div className=" justify-items-center">
        {data.subsections.map((item, index) => {
          const linkUrl = extractHref(item.description);

          return (
            <div key={index} className="text-center group relative mx-auto">
              <Link
                href={linkUrl}
                rel="noopener noreferrer"
                className="group relative block"
              >
                <h3
                  className={`text-[#0f2c3e] h-12 font-bold uppercase text-[17px] md:text-[24px] pb-16 md:pb-20 ${
                    index === 0 ? "" : ""
                  }`}
                  dangerouslySetInnerHTML={{ __html: item.title }}
                />
                <div className="relative overflow-hidden">
                  <Image
                    src={item.image || "/assets/images/placeholder.png"}
                    alt={item.title.replace(/<br\s*\/?>/gi, " ")}
                    width={620}
                    height={300}
                    className="w-[620px] h-[300px] object-cover transition-all duration-300"
                  />
                  <div className="absolute inset-0 md:bg-[rgba(58,111,147,0.85)] group-hover:bg-transparent transition-all duration-300"></div>
                </div>
              </Link>
            </div>
          );
        })}
      </div>
    </section>
  );
}
