"use client";

import Link from "next/link";
import { useLayoutEffect, useState } from "react";

function wrapTitleHtmlWithWordWeights(html: string): string {
  if (!html || typeof document === "undefined") return html;
  try {
    const parser = new DOMParser();
    const doc = parser.parseFromString(
      `<div id="__cta_title_root">${html}</div>`,
      "text/html"
    );
    const root = doc.getElementById("__cta_title_root");
    if (!root) return html;

    let wordCount = 0;
    const LIGHT_LIMIT = 5;

    function collectTextNodes(node: Node, out: Text[]) {
      if (node.nodeType === Node.TEXT_NODE) {
        out.push(node as Text);
        return;
      }
      if (node.nodeType !== Node.ELEMENT_NODE) return;
      const el = node as Element;
      if (el.tagName === "SCRIPT" || el.tagName === "STYLE") return;
      for (const child of Array.from(node.childNodes)) {
        collectTextNodes(child, out);
      }
    }

    function processTextNode(textNode: Text) {
      const text = textNode.data;
      if (!text) return;

      const parent = textNode.parentNode;
      if (!parent) return;

      const parts = text.split(/(\s+)/);
      const fragment = doc.createDocumentFragment();
      let buf = "";
      let bufClass: "light" | "medium" | null = null;

      function flushSpan() {
        if (buf === "") return;
        if (bufClass === null) {
          fragment.appendChild(doc.createTextNode(buf));
        } else {
          const span = doc.createElement("span");
          span.setAttribute(
            "class",
            bufClass === "light" ? "font-extralight" : "font-medium"
          );
          span.appendChild(doc.createTextNode(buf));
          fragment.appendChild(span);
        }
        buf = "";
        bufClass = null;
      }

      for (const part of parts) {
        if (part === "") continue;
        if (/^\s+$/.test(part)) {
          if (bufClass !== null && buf !== "") {
            buf += part;
          } else {
            flushSpan();
            fragment.appendChild(doc.createTextNode(part));
          }
          continue;
        }
        const isLight = wordCount < LIGHT_LIMIT;
        wordCount += 1;
        const cls: "light" | "medium" = isLight ? "light" : "medium";
        if (bufClass === cls) {
          buf += part;
        } else {
          flushSpan();
          bufClass = cls;
          buf = part;
        }
      }
      flushSpan();
      parent.insertBefore(fragment, textNode);
      parent.removeChild(textNode);
    }

    const textNodes: Text[] = [];
    collectTextNodes(root, textNodes);
    for (const tn of textNodes) {
      if (tn.parentNode) processTextNode(tn);
    }

    return root.innerHTML;
  } catch {
    return html;
  }
}

export default function CallToAction({ data }: { data?: any }) {
  if (!data) return null;

  const title = data.title || "";
  const [titleHtml, setTitleHtml] = useState(title);
  const description = data.description || "";
  const buttons = data.button?.items || [];

  useLayoutEffect(() => {
    setTitleHtml(wrapTitleHtmlWithWordWeights(title));
  }, [title]);

  return (
    <div className="relative z-20 mx-[20px] md:mx-[40px] -mb-90 md:-mb-30">
      <div className="bg-[#F7FAF8] rounded-[20px] border border-[#DAE6DC] shadow-2xl py-10 px-10 xl:max-w-[1240px] 2xl:max-w-[1440px] sm:mx-auto">
        <div className="flex flex-col lg:flex-row items-center justify-between gap-10">
 
          <div className="text-center lg:text-left">
            <span
              className="!text-black leading-tight text-[20px] md:text-[36px]"
              dangerouslySetInnerHTML={{ __html: titleHtml }}
            />
          </div>

          <div className="font-outfit w-full lg:w-auto">
            <p className="text-[#424242] leading-relaxed mb-10 font-light text-center lg:text-left">
              {description}
            </p>
 
            <div className="flex flex-col sm:flex-row gap-4 w-full  justify-center lg:justify-start">
              {buttons.map((btn: any, idx: number) => (
                <Link 
                  key={idx}
                  href={btn.button_url} 
                  className={idx === 0 
                    ? "flex items-center justify-center gap-3 md:gap-2 font-outfit sm:text-[18px] text-[14px] leading-[150%] text-center cursor-pointer border-2 border-[#0F3F32] bg-[#0F3F32] text-white p-[7px_7px_7px_15px] rounded-full font-semibold hover:border-2 hover:border-[#0F3F32] hover:bg-[#ffffff] hover:text-[#0F3F32] transition"
                    : "flex items-center justify-center gap-3 md:gap-2 font-outfit sm:text-[18px] text-[14px] leading-[150%] text-center cursor-pointer border-2 border-[#0F3F32] text-[#0F3F32] p-[7px_7px_7px_15px] rounded-full font-semibold hover:bg-[#0F3F32] hover:text-white transition"
                  }
                >
                  {btn.button_text}
                  <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>
                </Link>
              ))}
            </div>
          </div>
 
        </div>
      </div>
    </div>
  );
}