import Link from "next/link";
import ServiceCard from "./ServiceCard";

const IconArrowRight = () => (
    <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
        <path d="M0 18C0 8.05887 8.05887 0 18 0V0C27.9411 0 36 8.05887 36 18V18C36 27.9411 27.9411 36 18 36V36C8.05887 36 0 27.9411 0 18V18Z" fill="#F7FAF8" />
        <path d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5" stroke="#053F31" strokeWidth="2" />
    </svg>
);

interface SignupComponentProps {
    data?: any;
}

const getFirstNestedItem = (value: any): any => {
    if (!value) return null;
    if (Array.isArray(value)) return getFirstNestedItem(value[0]);
    if (typeof value === "object" && Array.isArray(value.items)) return getFirstNestedItem(value.items[0]);
    if (typeof value === "object") {
        const keys = Object.keys(value);
        for (const key of keys) {
            const nested = getFirstNestedItem(value[key]);
            if (nested && typeof nested === "object" && Object.keys(nested).length > 0) return nested;
        }
    }
    return value;
};

const extractListFromHtml = (html?: string) => {
    if (!html) return undefined;
    const matches = [...html.matchAll(/<li\b[^>]*>([\s\S]*?)<\/li>/gi)];
    if (!matches.length) return undefined;
    const items = matches
        .map((m) =>
            m[1]
                .replace(/<[^>]+>/g, "")
                .replace(/&nbsp;/g, " ")
                .trim()
        )
        .filter(Boolean);
    return items.length ? items : undefined;
};

const SignupComponent: React.FC<SignupComponentProps> = ({ data }) => {
    const buttonItem = getFirstNestedItem(data?.button) ?? {};
    const buttonLabel = buttonItem?.button_text || "";
    const buttonHref = buttonItem?.button_url || "";
    const listFromApi = extractListFromHtml(data?.richtext);
    return (
        <div className="w-full lg:max-w-[450px] xl:max-w-[605px] 2xl:max-w-[605px]">
            <ServiceCard
                icon={data?.logo_svg ? <div dangerouslySetInnerHTML={{ __html: data.logo_svg }} style={{ padding: "15px"}}/> : null}
                title={data?.title || ""}
                list={listFromApi}
                ordered
                className="bg-[#F7FAF8] xl:max-h-[353px] xl:min-h-[353px] md:max-h-[415px] md:min-h-[415px] flex flex-col justify-between py-8"
                action={
                    <Link
                        href={buttonHref}
                        className="inline-flex items-center justify-center gap-[10px] bg-[#053F31] font-outfit text-[18px] leading-[150%] text-white font-semibold p-[7px_7px_7px_15px] cursor-pointer rounded-full border-2 hover:border-[#0F3F32] hover:bg-[#ffffff] hover:text-[#0F3F32] transition"
                    >
                        {buttonLabel}
                        <IconArrowRight />
                    </Link>
                }
            />
        </div>
    )
};

export default SignupComponent;
