"use client";
import Image from "next/image";
import { useState, useEffect, useRef, FormEvent } from "react";
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { QRCodeCanvas } from "qrcode.react";
import { domToPng } from "modern-screenshot";
import SafeHtmlRenderer from "../SafeHtmlRenderer";
import {
  RefreshCw,
  User,
  Mail,
  Phone,
  Building2,
  MessageSquare,
} from "lucide-react";
import useAxios from "@/hooks/useAxios";
import axios from "axios";
import { BASE_URL, BASE_URL2 } from "@/Constant";
import Loading from "@/app/loading";
import { toast, ToastContainer } from "react-toastify";
import Loader from "../../components/Loader/Loader";

// Types and Interfaces
interface FormDataType {
  accreditationId: string;
  name: string;
  contactNo: string;
  emailId: string;
  companyName: string;
  subject: string;
  memberenquiry: string;
  captcha: string;
  memberenquiryFrom: string;
}

interface AccreditationType {
  _id?: string;
  uniqueID?: string;
  clientLogo?: string;
  cFirstName?: string;
  cLastName?: string;
  cEmail?: string;
  oFullName?: string;
  organisationName?: string;
  displayName?: string;
  isVerified?: boolean;
  sDate?: string;
  KeyLocation?: Array<{
    country?: string;
    state?: string;
    city?: string;
  }>;
  [key: string]: any;
}

interface MemberPageDataType {
  CardImage?: string;
  [key: string]: any;
}

interface CaptchaResponseType {
  captcha?: string;
}

interface CountryType {
  billcountryid: string;
  billcountry: string;
  [key: string]: any;
}

interface StateType {
  billstateid: string;
  billstate: string;
  [key: string]: any;
}

interface CityType {
  billcityid: string;
  billcity: string;
  [key: string]: any;
}

interface ApiResponseType<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  [key: string]: any;
}

interface ImageBase64Response {
  image?: string;
}

interface AxiosGetResponse<T = any> {
  data?: T;
  success?: boolean;
  [key: string]: any;
}

// Component Props
interface InnerAboutProps {
  slug: any;
}

export default function InnerAbout({ slug }: InnerAboutProps) {
  const cardRef = useRef<HTMLDivElement>(null);
  const [formData, setFormData] = useState<FormDataType>({
    accreditationId: "",
    name: "",
    contactNo: "",
    emailId: "",
    companyName: "",
    subject: "",
    memberenquiry: "",
    captcha: "",
    memberenquiryFrom: "Organisation Member",
  });

  const [accreditation, setAccreditation] = useState<AccreditationType | null>(
    null,
  );
  const [captchaSvg, setCaptchaSvg] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [currentUrl, setCurrentUrl] = useState<string>("");

  // Digital Card States
  const [postImage, setPostImage] = useState<MemberPageDataType | null>(null);
  const [postImageBase64, setPostImageBase64] = useState<string | null>(null);
  const [logoBase64, setLogoBase64] = useState<string | null>(null);

  const [countries, setCountries] = useState<CountryType[]>([]);
  const [states, setStates] = useState<Record<string, StateType[]>>({});
  const [cities, setCities] = useState<Record<string, CityType[]>>({});

  const { postData, getData } = useAxios();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [notFound, setNotFound] = useState<boolean>(false);
  const router = useRouter();
  const [websiteData, setWebsiteData] = useState<WebsiteData | null>(null);

  const fetchWebsite = async (): Promise<void> => {
    try {
      const res = await axios.get<ApiResponse<WebsiteData>>(
        `${BASE_URL}website/getWebsiteById?websiteId=66e3e5bfcdfd3a17049f0279`,
      );
      setWebsiteData(res?.data?.data || null);
    } catch (err) {
      console.error("Website fetch error", err);
    }
  };

  // Fetch member page data for card image
  useEffect(() => {
    async function fetchMemberPageData() {
      try {
        const res = await fetch(
          `${BASE_URL}memberPageData/67c948c9d79a4823c991f407`,
        );
        const json = await res.json();

        if (json?.success && json?.data) {
          setPostImage(json.data);

          // Handle CardImage if it exists
          if (json.data.CardImage) {
            const formattedPath = json.data.CardImage.replace(/\\/g, "/");
            const filename = formattedPath.split("/").pop();

            try {
              const imgRes = await fetch(`${BASE_URL}image-base64/${filename}`);
              const imgJson: ImageBase64Response = await imgRes.json();

              if (imgJson.image) {
                setPostImageBase64(imgJson.image);
              }
            } catch (base64Err) {
              console.error("CardImage base64 fetch error:", base64Err);
            }
          }
        }
      } catch (err) {
        console.error("Member page data fetch error", err);
      }
    }

    fetchMemberPageData();
  }, []);

  // Convert organization logo to base64
  useEffect(() => {
    async function fetchLogo() {
      if (accreditation?.clientLogo) {
        const filename = accreditation.clientLogo.split("/").pop();

        try {
          const res = await fetch(`${BASE_URL}image-base64/${filename}`);
          const json: ImageBase64Response = await res.json();

          if (json.image) {
            setLogoBase64(json.image);
          }
        } catch (err) {
          console.error("Logo fetch error", err);
        }
      }
    }

    fetchLogo();
  }, [accreditation?.clientLogo]);

  const redirectTo404 = (): void => {
    setNotFound(true);
    router.push("/404");
  };

  const fetchAllCountries = async (): Promise<void> => {
    try {
      const res: AxiosGetResponse<CountryType[]> = await getData(
        "dropdown/getAllCountry",
      );
      if (res?.success && Array.isArray(res.data)) {
        setCountries(res.data);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const fetchStates = async (countryId: string, key: string): Promise<void> => {
    try {
      const res: AxiosGetResponse<StateType[]> = await getData(
        `dropdown/getAllStates?billcountryid=${countryId}`,
      );
      if (res?.success) {
        setStates((prev) => ({ ...prev, [key]: res.data || [] }));
      }
    } catch (err) {
      console.error(err);
    }
  };

  const fetchCities = async (stateId: string, key: string): Promise<void> => {
    try {
      const res: AxiosGetResponse<CityType[]> = await getData(
        `dropdown/getAllCity?billstateid=${stateId}`,
      );
      if (res?.success) {
        setCities((prev) => ({ ...prev, [key]: res.data || [] }));
      }
    } catch (err) {
      console.error(err);
    }
  };

  // --- Mappers ---
  const getCountryName = (billcountryid: string): string => {
    if (!billcountryid) return "-";
    const c = countries.find(
      (c) => String(c.billcountryid) === String(billcountryid),
    );
    return c ? c.billcountry : billcountryid;
  };

  const getStateName = (billstateid: string, index: number): string => {
    if (!billstateid) return "-";
    const s = states[`state-${index}`]?.find(
      (st) => String(st.billstateid) === String(billstateid),
    );
    return s ? s.billstate : billstateid;
  };

  const getCityName = (billcityid: string, index: number): string => {
    if (!billcityid) return "-";
    const c = cities[`city-${index}`]?.find(
      (ct) => String(ct.billcityid) === String(billcityid),
    );
    return c ? c.billcity : billcityid;
  };

  const extractUniqueId = (slug: string): string => {
    const parts = slug.split("/");
    return parts[parts.length - 1]; // Last part is the unique ID
  };

  const fetchAccreditation = async (): Promise<void> => {
    try {
      if (slug) {
        const uniqueID = extractUniqueId(slug);

        // ✅ Check if it's IAAB type - then use uniqueID parameter
        if (uniqueID.startsWith("IAAB")) {
          const response = await axios.get<ApiResponseType<AccreditationType>>(
            `${BASE_URL}association-member/searchASSBySlug?uniqueId=${uniqueID}`,
          );

          if (response.data.success) {
            const acc = response.data.data;
            setAccreditation(acc || null);
            setFormData((prev) => ({
              ...prev,
              accreditationId: acc?._id || "",
            }));
            console.log("IAAB Association Data:", acc);
          }
        }
        // ✅ Else use slug parameter
        else {
          const response = await axios.get<ApiResponseType<AccreditationType>>(
            `${BASE_URL}association-member/searchASSBySlug?slug=${slug}`,
          );

          if (response.data.success) {
            const acc = response.data.data;
            setAccreditation(acc || null);
            setFormData((prev) => ({
              ...prev,
              accreditationId: acc?._id || "",
            }));
            console.log("Slug Association Data:", acc);
          }
        }
      }
    } catch (error) {
      console.log("Association fetch error:", error);
      redirectTo404();
    }
  };

  const fetchAccreditation2 = async (): Promise<void> => {
    try {
      if (slug) {
        const response = await axios.get<ApiResponseType<AccreditationType>>(
          `${BASE_URL}cb/searchCbBySlug2?slug=${slug}`,
        );

        if (response.data.success) {
          const acc = response.data.data;
          setAccreditation(acc || null);
          setFormData((prev) => ({
            ...prev,
            accreditationId: acc?._id || "",
          }));

          acc?.KeyLocation?.forEach((loc: any, i: number) => {
            if (loc.country) fetchStates(loc.country, `state-${i}`);
            if (loc.state) fetchCities(loc.state, `city-${i}`);
          });
        }
      }
    } catch (error) {
      console.log("CB fetch error:", error);
    }
  };

  const fetchCaptcha = async (): Promise<void> => {
    try {
      const { data }: { data?: CaptchaResponseType } = await getData(
        "captcha/generateCaptcha",
        {
          withCredentials: true,
        },
      );
      setCaptchaSvg(data?.captcha || "");
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchAllCountries();
    fetchCaptcha();
    fetchWebsite();
    fetchAccreditation().then(() => {
      if (!accreditation) {
        fetchAccreditation2();
      }
    });
  }, [slug]);

  useEffect(() => {
    if (typeof window !== "undefined" && accreditation?.uniqueID) {
      const params = searchParams?.toString();
      const url = `${window.location.origin}${pathname}${
        params ? `?${params}` : ""
      }`;
      setCurrentUrl(url);
    }
  }, [pathname, searchParams, accreditation?.uniqueID]);

  const handleSubmit = async (e: FormEvent<HTMLFormElement>): Promise<void> => {
    e.preventDefault();

    // ✅ REQUIRED FIELDS VALIDATION - Company name ko chod ke sab required
    if (!formData.name.trim()) {
      toast.error("Name is required");
      return;
    }
    if (!formData.contactNo.trim()) {
      toast.error("Contact number is required");
      return;
    }
    if (!formData.emailId.trim()) {
      toast.error("Email is required");
      return;
    }
    // ✅ Company name optional hai - isko check nahi karenge
    if (!formData.subject.trim()) {
      toast.error("Subject is required");
      return;
    }
    if (!formData.memberenquiry.trim()) {
      toast.error("Enquiry is required");
      return;
    }
    if (!formData.captcha.trim()) {
      toast.error("Captcha is required");
      return;
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.emailId)) {
      toast.error("Please enter a valid email address");
      return;
    }

    setLoading(true);
    try {
      const res: any = await postData("memberenquiry", formData, {
        withCredentials: true,
      });

      if (res?.success) {
        setFormData({
          accreditationId: accreditation?._id || "",
          name: "",
          contactNo: "",
          emailId: "",
          companyName: "",
          subject: "",
          memberenquiry: "",
          captcha: "",
          memberenquiryFrom: "Organisation Member",
        });
        toast.success(res?.message);
      } else {
        toast.error(res?.message);
      }
    } catch (error) {
      console.error(error);
      toast.error("Error submitting form");
    } finally {
      setLoading(false);
      fetchCaptcha();
    }
  };

  // Helper function for card icons
  const getIconUrl = (iconPath: string): string => {
    if (typeof window !== "undefined") {
      return `${window.location.origin}${iconPath}`;
    }
    return iconPath;
  };

  const getLogoUrl = (path?: string): string | null => {
    if (!path) return null;
    const cleanPath = String(path).replace(/\\/g, "/");
    if (cleanPath.startsWith("http")) return cleanPath;
    return `${BASE_URL}${cleanPath}`;
  };

  const formatDateCard = (dateString?: string): string => {
    if (!dateString) return "31st January 2026";

    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return "31st January 2026";

      const day = date.getDate();
      const month = date.toLocaleString("default", { month: "long" });
      const year = date.getFullYear();

      const getOrdinalSuffix = (day: number): string => {
        if (day >= 11 && day <= 13) return "th";
        switch (day % 10) {
          case 1:
            return "st";
          case 2:
            return "nd";
          case 3:
            return "rd";
          default:
            return "th";
        }
      };

      const suffix = getOrdinalSuffix(day);
      return `${day}${suffix} ${month} ${year}`;
    } catch (error) {
      return "31st January 2026";
    }
  };

  // Get full name from the API response data
  const getFullName = (): string => {
    if (accreditation?.cFirstName && accreditation?.cLastName) {
      return `${accreditation.cFirstName} ${accreditation.cLastName}`;
    }
    return (
      accreditation?.cFirstName ||
      accreditation?.oFullName ||
      accreditation?.displayName ||
      "Organization"
    );
  };

  if (!accreditation) return <Loading />;

  return (
    <>
      {/* Digital Card Styles */}
      <style jsx global>{`
        @import url("https://fonts.googleapis.com/css2?family=Libre+Baskerville:wght@400;700&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap");

        .certificate-card {
          background-image: url("/bg87.png") !important;
          background-size: cover !important;
          background-position: center !important;
          background-repeat: no-repeat !important;
          width: 641px !important;
          height: 384px !important;
          min-width: 485px !important;
          min-height: 352px !important;
        }
        @media (max-width: 640px) {
          .certificate-card {
            transform: scale(0.8);
            transform-origin: top center;
          }

          .certificate-card {
            min-height: 100px !important;
            min-width: 652px !important;
            margin-left: 152px;
          }

          .card-content {
            padding: 20px 10px 8px 35px !important;
          }

          .header-title {
            font-size: 12px !important;
            margin-left: -20px !important;
          }

          .profile-image {
            width: 80px !important;
            height: 80px !important;
          }

          .qr-code canvas {
            width: 90px !important;
            height: 90px !important;
          }

          .org-logo {
            width: 70px !important;
            height: 70px !important;
          }
          .mobileONLy {
            overflow: scroll !important;
          }
        }
        .detail-icon {
          width: 20px !important;
          height: 20px !important;
          min-width: 20px !important;
          object-fit: contain;
          display: block;
          flex-shrink: 0;
        }

        .card-content {
          padding: 24px 14px 8px 45px !important;
        }

        .header-title {
          font-size: 14px !important;
          margin-left: -26px !important;
          line-height: 1.3 !important;
        }

        .profile-image {
          width: 100px !important;
          height: 100px !important;
        }

        .profile-initial {
          font-size: 48px !important;
        }

        .role-title {
          font-size: 15px !important;
          margin-top: 5px !important;
          margin-bottom: 5px !important;
          width: 440px !important;
        }

        .detail-text {
          font-size: 13px !important;
          line-height: 1.4 !important;
        }

        .org-logo {
          width: 90px !important;
          height: 90px !important;
        }

        .qr-container {
          padding: 11px !important;
        }

        .qr-code canvas {
          width: 110px !important;
          height: 110px !important;
        }

        .detail-row {
          gap: 8px !important;
          margin-bottom: 8px !important;
        }

        .space-y-custom > * + * {
          margin-top: 8px !important;
        }

        .right-section {
          gap: 16px !important;
          padding-top: 4px !important;
        }
      `}</style>

      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4 md:px-8">
        {/* Sirf Digital Card View */}
        <div className="flex flex-col items-center">
          {/* Card */}
          <div
            className="flex justify-center bg-white/90 w-full mobileONLy"
            style={{ overflowX: "auto", padding: "0 16px" }}
          >
            <div
              ref={cardRef}
              className="certificate-card relative shadow-2xl overflow-hidden"
              style={{
                width: "616px",
                height: "452px",
                minWidth: "616px",
                minHeight: "452px",
                backgroundImage: "url('/backgroundPNG.png')",
                backgroundSize: "cover",
                backgroundPosition: "center",
                backgroundRepeat: "no-repeat",
                position: "relative",
              }}
            >
              <div
                className="card-content relative z-10"
                style={{ padding: "24px 14px 8px 45px" }}
              >
                {/* HEADER */}
                <div className="text-center mb-6">
                  <h4
                    className="header-title"
                    style={{
                      color: "rgba(3, 47, 78, 1)",
                      fontFamily: "'Libre Baskerville', serif",
                      fontSize: "14px",
                      fontWeight: "700",
                      lineHeight: "1.3",
                      marginLeft: "-26px",
                    }}
                  >
                    INTERNATIONAL ASSOCIATION FOR ASSESSMENT BOARD
                  </h4>
                </div>

                {/* MAIN CONTENT GRID */}
                <div className="grid grid-cols-2 gap-0">
                  {/* LEFT SECTION */}
                  <div className="space-y-4">
                    <div className="flex justify-start">
                      <div
                        className="profile-image"
                        style={{
                          width: "100px",
                          height: "100px",
                          borderRadius: "8px",
                          overflow: "hidden",
                          backgroundColor: "#fff",
                          border: "2px solid #e5e7eb",
                        }}
                      >
                        {accreditation.clientLogo ? (
                          <img
                            src={
                              logoBase64 ||
                              getLogoUrl(accreditation.clientLogo) ||
                              ""
                            }
                            alt="Profile"
                            style={{
                              width: "100%",
                              height: "100%",
                              objectFit: "cover",
                            }}
                            onError={(e) => {
                              console.log(
                                "Profile image error, using fallback",
                              );
                              if (!logoBase64) {
                                (e.target as HTMLImageElement).src =
                                  getLogoUrl(accreditation.clientLogo) || "";
                              }
                            }}
                          />
                        ) : (
                          <div
                            className="profile-initial"
                            style={{
                              width: "100%",
                              height: "100%",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              fontSize: "48px",
                              fontWeight: "700",
                              color: "rgba(7, 59, 89, 1)",
                              backgroundColor: "#f0f4ff",
                              fontFamily: "'Plus Jakarta Sans', sans-serif",
                            }}
                          >
                            {getFullName().charAt(0)}
                          </div>
                        )}
                      </div>
                    </div>

                    {/* ROLE/TYPE */}
                    <div
                      style={{
                        marginTop: "5px",
                        width: "440px",
                      }}
                    >
                      <h2
                        className="role-title"
                        style={{
                          color: "rgba(3, 47, 78, 1)",
                          fontFamily: "'Libre Baskerville', serif",
                          fontSize: "15px",
                          fontWeight: "700",
                          marginBottom: "5px",
                        }}
                      >
                        Organization Member
                      </h2>
                    </div>

                    {/* USER DETAILS */}
                    <div
                      className="space-y-custom space-y-2"
                      style={{ marginTop: "5px" }}
                    >
                      <div className="detail-row flex items-start gap-2">
                        <img
                          src={getIconUrl("/wpf_name.svg")}
                          alt="Name"
                          className="detail-icon"
                          crossOrigin="anonymous"
                          style={{ marginTop: "0px" }}
                        />
                        <div
                          className="detail-text"
                          style={{
                            lineHeight: "1.4",
                            fontSize: "13px",
                            fontFamily: "'Plus Jakarta Sans', sans-serif",
                          }}
                        >
                          <span
                            style={{
                              fontWeight: "600",
                              color: "rgba(7, 59, 89, 1)",
                            }}
                          >
                            Organization Name:{" "}
                          </span>
                          <span
                            style={{
                              color: "rgba(7, 59, 89, 1)",
                              fontWeight: "400",
                            }}
                          >
                            {accreditation.oFullName ||
                              accreditation.organisationName ||
                              "N/A"}
                          </span>
                        </div>
                      </div>

                      <div className="detail-row flex items-start gap-2">
                        <img
                          src={getIconUrl("/wpf_name.svg")}
                          alt="Name"
                          className="detail-icon"
                          crossOrigin="anonymous"
                          style={{ marginTop: "0px" }}
                        />
                        <div
                          className="detail-text"
                          style={{
                            lineHeight: "1.4",
                            fontSize: "13px",
                            fontFamily: "'Plus Jakarta Sans', sans-serif",
                          }}
                        >
                          <span
                            style={{
                              fontWeight: "600",
                              color: "rgba(7, 59, 89, 1)",
                            }}
                          >
                            Name:{" "}
                          </span>
                          <span
                            style={{
                              color: "rgba(7, 59, 89, 1)",
                              fontWeight: "400",
                            }}
                          >
                            {getFullName()}
                          </span>
                        </div>
                      </div>

                      <div className="detail-row flex items-start gap-2">
                        <img
                          src={getIconUrl("/roentgen_phone.svg")}
                          alt="Unique ID"
                          className="detail-icon"
                          crossOrigin="anonymous"
                          style={{ marginTop: "0px" }}
                        />
                        <div
                          className="detail-text"
                          style={{
                            lineHeight: "1.4",
                            fontSize: "13px",
                            fontFamily: "'Plus Jakarta Sans', sans-serif",
                          }}
                        >
                          <span
                            style={{
                              fontWeight: "600",
                              color: "rgba(7, 59, 89, 1)",
                            }}
                          >
                            Unique Id:{" "}
                          </span>
                          <span
                            style={{
                              color: "rgba(7, 59, 89, 1)",
                              fontWeight: "400",
                            }}
                          >
                            {accreditation.uniqueID || "N/A"}
                          </span>
                        </div>
                      </div>

                      <div className="detail-row flex items-start gap-2">
                        <img
                          src={getIconUrl("/Icons (1).svg")}
                          alt="Email"
                          className="detail-icon"
                          crossOrigin="anonymous"
                          style={{ marginTop: "0px" }}
                        />
                        <div
                          className="detail-text"
                          style={{
                            lineHeight: "1.4",
                            fontSize: "13px",
                            fontFamily: "'Plus Jakarta Sans', sans-serif",
                          }}
                        >
                          <span
                            style={{
                              fontWeight: "600",
                              color: "rgba(7, 59, 89, 1)",
                            }}
                          >
                            Email Id:{" "}
                          </span>
                          <span
                            style={{
                              color: "rgba(7, 59, 89, 1)",
                              fontWeight: "400",
                              wordBreak: "break-all",
                            }}
                          >
                            {accreditation.cEmail || "N/A"}
                          </span>
                        </div>
                      </div>

                      {/* <div className="detail-row flex items-start gap-2">
                        <img
                          src={getIconUrl("/clarity_date-solid.svg")}
                          alt="Date"
                          className="detail-icon"
                          crossOrigin="anonymous"
                          style={{ marginTop: "0px" }}
                        />
                        <div
                          className="detail-text"
                          style={{
                            lineHeight: "1.4",
                            fontSize: "13px",
                            fontFamily: "'Plus Jakarta Sans', sans-serif",
                          }}
                        >
                          <span
                            style={{
                              fontWeight: "600",
                              color: "rgba(7, 59, 89, 1)",
                            }}
                          >
                            Date of Certificate:{" "}
                          </span>
                          <span
                            style={{
                              color: "rgba(7, 59, 89, 1)",
                              fontWeight: "400",
                            }}
                          >
                            {accreditation.sDate
                              ? formatDateCard(accreditation.sDate)
                              : "31st January 2026"}
                          </span>
                        </div>
                      </div> */}

                      <div className="detail-row flex items-start gap-2">
                        <img
                          src={getIconUrl("/streamline-plump_web-solid.svg")}
                          alt="Website"
                          className="detail-icon"
                          crossOrigin="anonymous"
                        />
                        <div className="detail-text">
                          <span
                            style={{
                              fontWeight: "600",
                              color: "rgba(7, 59, 89, 1)",
                            }}
                          >
                            Website:{" "}
                          </span>
                          <span
                            style={{
                              color: "rgba(7, 59, 89, 1)",
                              fontWeight: "400",
                              wordBreak: "break-all",
                            }}
                          >
                            {websiteData?.website || "https://iaabweb.work4node.in/"}
                          </span>
                        </div>
                      </div>

                      {/* <div className="detail-row flex items-start gap-2">
                        <img
                          src={getIconUrl("/streamline-plump_web-solid.svg")}
                          alt="Website"
                          className="detail-icon"
                          crossOrigin="anonymous"
                          style={{ marginTop: "0px" }}
                        />
                        <div
                          className="detail-text"
                          style={{
                            lineHeight: "1.4",
                            fontSize: "13px",
                            fontFamily: "'Plus Jakarta Sans', sans-serif",
                          }}
                        >
                          <span
                            style={{
                              fontWeight: "600",
                              color: "rgba(7, 59, 89, 1)",
                            }}
                          >
                            Certification Status:{" "}
                          </span>
                          <span
                            style={{
                              color: accreditation.isVerified
                                ? "#28a745"
                                : "#dc3545",
                              fontWeight: "500",
                              wordBreak: "break-all",
                            }}
                          >
                            {accreditation.isVerified ? "ACTIVE" : "INACTIVE"}
                          </span>
                        </div>
                      </div> */}
                    </div>
                  </div>

                  {/* RIGHT SECTION */}
                  <div
                    className="right-section"
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      justifyContent: "space-between",
                      gap: "16px",
                      paddingTop: "4px",
                    }}
                  >
                    {/* ORGANIZATION LOGO */}
                    {postImage && (
                      <div
                        className="org-logo"
                        style={{
                          width: "90px",
                          height: "90px",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                        }}
                      >
                        <img
                          src={postImageBase64 || (postImage as any)}
                          style={{
                            maxWidth: "100%",
                            maxHeight: "100%",
                            objectFit: "contain",
                          }}
                          alt="Certificate Image"
                          onError={(e) => {
                            console.log(
                              "Post image error, trying fallback URL",
                            );
                            if (
                              (e.target as HTMLImageElement).src ===
                                postImageBase64 &&
                              postImage
                            ) {
                              (e.target as HTMLImageElement).src =
                                postImage as any;
                            }
                          }}
                        />
                      </div>
                    )}

                    {/* QR CODE */}
                    <div
                      className="qr-container"
                      style={{
                        backgroundColor: "rgba(245, 224, 226, 0.3)",
                        padding: "11px",
                        borderRadius: "10px",
                        border: "2px solid rgba(245, 224, 226, 1)",
                      }}
                    >
                      <div className="qr-code">
                        <QRCodeCanvas
                          value={currentUrl}
                          size={110}
                          level="H"
                          includeMargin={false}
                          style={{
                            backgroundColor: "rgba(245, 224, 226, 0.3)",
                          }}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Enquiry Form - Niche */}
          <div className="w-full mx-auto mt-8">
            {accreditation.organisationProfile && (
              <section className="mb-8">
                <h2 className="text-xl font-bold text-slate-800 mb-2">
                  About Info
                </h2>
                <div className="bg-slate-50 rounded-xl p-6 flex-wrap sm:flex-nowrap">
                  <p className="text-slate-700">
                    {accreditation.organisationProfile}
                  </p>
                </div>
              </section>
            )}
            <div
              className="bg-gradient-to-r from-slate-50 to-blue-50 rounded-2xl p-4 border border-slate-200"
              style={{ backgroundColor: "beige" }}
            >
              <h2 className="text-lg font-semibold mb-3">Get In Touch</h2>
              <form onSubmit={handleSubmit} className="space-y-5 md:space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-5">
                  <div>
                    <label
                      htmlFor="name"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-1"
                    >
                      <User className="w-4 h-4 text-blue-600" />
                      Name <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="name"
                      placeholder="Enter your full name"
                      className="w-full px-2 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.name}
                      onChange={(e) =>
                        setFormData({ ...formData, name: e.target.value })
                      }
                      required
                    />
                  </div>
                  <div>
                    <label
                      htmlFor="emailId"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-1"
                    >
                      <Mail className="w-4 h-4 text-blue-600" />
                      Email <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="email"
                      id="emailId"
                      placeholder="Enter email address"
                      className="w-full px-2 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.emailId}
                      onChange={(e) =>
                        setFormData({ ...formData, emailId: e.target.value })
                      }
                      required
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-5">
                  <div>
                    <label
                      htmlFor="contactNo"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-1"
                    >
                      <Phone className="w-4 h-4 text-blue-600" />
                      Phone <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="contactNo"
                      placeholder="Enter contact number"
                      className="w-full px-2 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.contactNo}
                      onChange={(e) =>
                        setFormData({ ...formData, contactNo: e.target.value })
                      }
                      required
                    />
                  </div>

                  <div>
                    <label
                      htmlFor="companyName"
                      className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-1"
                    >
                      <Building2 className="w-4 h-4 text-blue-600" />
                      Company
                    </label>
                    <input
                      type="text"
                      id="companyName"
                      placeholder="Enter company name (optional)"
                      className="w-full px-2 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.companyName}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          companyName: e.target.value,
                        })
                      }
                    />
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="subject"
                    className="block text-sm font-medium text-slate-700 mb-1"
                  >
                    Subject <span className="text-red-500">*</span>
                  </label>
                  <select
                    id="subject"
                    className="w-full px-2 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                    value={formData.subject}
                    onChange={(e) =>
                      setFormData({ ...formData, subject: e.target.value })
                    }
                    required
                  >
                    <option value="">Select Subject</option>
                    <option value="General">General Enquiry</option>
                    <option value="Support">Support</option>
                    <option value="Feedback">Feedback</option>
                    <option value="Appeal">Appeal</option>
                    <option value="Complaint">Complaint</option>
                  </select>
                </div>

                <div>
                  <label
                    htmlFor="memberenquiry"
                    className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-1"
                  >
                    <MessageSquare className="w-4 h-4 text-blue-600" />
                    Enquiry Details <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    id="memberenquiry"
                    placeholder="Write your enquiry here..."
                    rows={3}
                    className="w-full px-2 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white resize-none"
                    value={formData.memberenquiry}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        memberenquiry: e.target.value,
                      })
                    }
                    required
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-5 items-center">
                  <div>
                    <label
                      htmlFor="captcha"
                      className="block text-sm font-medium text-slate-700 mb-1"
                    >
                      Captcha <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="captcha"
                      placeholder="Enter captcha"
                      className="w-full px-2 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm bg-white"
                      value={formData.captcha}
                      onChange={(e) =>
                        setFormData({ ...formData, captcha: e.target.value })
                      }
                      required
                    />
                  </div>

                  <div className="flex items-center gap-3 mt-1">
                    <SafeHtmlRenderer htmlContent={captchaSvg} />
                    <button
                      type="button"
                      onClick={fetchCaptcha}
                      className="p-2.5 rounded-lg hover:bg-slate-100 transition border border-slate-200"
                      aria-label="Regenerate Captcha"
                    >
                      <RefreshCw className="w-4 h-4 text-slate-600" />
                    </button>
                  </div>
                </div>

                {loading ? (
                  <div className="flex justify-center">
                    <Loader />
                  </div>
                ) : (
                  <button
                    type="submit"
                    className="px-6 py-2 bg-iaab-gradient rounded-xl border border-gray-300 hover:border-gray-400 shadow-sm disabled:opacity-60"
                  >
                    Send Message
                  </button>
                )}
              </form>

              <ToastContainer />
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
