"use client";
import Image from "next/image";
import { useState, useEffect, useRef } from "react";
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { QRCodeCanvas } from "qrcode.react";
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";

// Interface Definitions
interface FormData {
  accreditationId: string;
  name: string;
  contactNo: string;
  emailId: string;
  companyName: string;
  subject: string;
  memberenquiry: string;
  captcha: string;
  memberenquiryFrom: string;
}

interface Accreditation {
  _id?: string;
  clientLogo?: string;
  cFirstName?: string;
  cLastName?: string;
  oFullName?: string;
  displayName?: string;
  cEmail?: string;
  uniqueID?: string;
  sDate?: string;
  status?: boolean;
  type?: string;
  organisationProfile?: string;
  standards?: any[];
  KeyLocation?: KeyLocation[];
  [key: string]: any;
}

interface KeyLocation {
  country?: string;
  state?: string;
  city?: string;
  address?: string;
}

interface Country {
  billcountryid: string;
  billcountry: string;
}

interface State {
  billstateid: string;
  billstate: string;
}

interface City {
  billcityid: string;
  billcity: string;
}

interface WebsiteData {
  website?: string;
  [key: string]: any;
}

interface PostImage {
  CardImage?: string;
  [key: string]: any;
}

interface StandardItem {
  glaApprovalStatus?: string;
  [key: string]: any;
}

interface CaptchaResponse {
  captcha?: string;
}

interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
}

interface Props {
  slug: any;
}

export default function InnerAbout({ slug }: Props) {
  const [formData, setFormData] = useState<FormData>({
    accreditationId: "",
    name: "",
    contactNo: "",
    emailId: "",
    companyName: "",
    subject: "",
    memberenquiry: "",
    captcha: "",
    memberenquiryFrom: "Association Member",
  });

  const [accreditation, setAccreditation] = useState<Accreditation | null>(
    null,
  );
  const [captchaSvg, setCaptchaSvg] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [currentUrl, setCurrentUrl] = useState<string>("");
  const [websiteData, setWebsiteData] = useState<WebsiteData | null>(null);
  const [logoBase64, setLogoBase64] = useState<string | null>(null);
  const [postImage, setPostImage] = useState<PostImage | null>(null);
  const [postImageBase64, setPostImageBase64] = useState<string | null>(null);

  const [notFound, setNotFound] = useState<boolean>(false);
  const router = useRouter();

  const redirectTo404 = (): void => {
    setNotFound(true);
    router.push("/404");
  };

  const [countries, setCountries] = useState<Country[]>([]);
  const [states, setStates] = useState<Record<string, State[]>>({});
  const [cities, setCities] = useState<Record<string, City[]>>({});

  const { postData, getData } = useAxios();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // Fetch website data
  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 post image
  const fetchMemberPageData = async (): Promise<void> => {
    try {
      const res = await axios.get<ApiResponse<PostImage>>(
        `${BASE_URL}memberPageData/67c9486cd79a4823c991f405`,
      );

      if (res?.data?.success && res?.data?.data) {
        setPostImage(res.data.data);

        if (res.data.data.CardImage) {
          const formattedPath = res.data.data.CardImage.replace(/\\/g, "/");
          const filename = formattedPath.split("/").pop();

          if (filename) {
            try {
              const imgRes = await axios.get<{ image: string }>(
                `${BASE_URL}image-base64/${filename}`,
              );
              if (imgRes.data.image) {
                setPostImageBase64(imgRes.data.image);
              }
            } catch (base64Err) {
              console.error("CardImage base64 fetch error:", base64Err);
            }
          }
        }
      }
    } catch (err) {
      console.error("Member page data fetch error", err);
    }
  };

  // Convert logo to base64
  useEffect(() => {
    async function fetchLogo(): Promise<void> {
      if (accreditation?.clientLogo) {
        const filename = accreditation.clientLogo.split("/").pop();

        if (filename) {
          try {
            const res = await axios.get<{ image: string }>(
              `${BASE_URL}image-base64/${filename}`,
            );
            if (res.data.image) {
              setLogoBase64(res.data.image);
            }
          } catch (err) {
            console.error("Logo fetch error", err);
          }
        }
      }
    }

    if (accreditation?.clientLogo) {
      fetchLogo();
    }
  }, [accreditation?.clientLogo]);

  const fetchAllCountries = async (): Promise<void> => {
    try {
      const res: ApiResponse<Country[]> = 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: ApiResponse<State[]> = 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: ApiResponse<City[]> = 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 =
      index !== undefined
        ? states[`state-${index}`]?.find(
            (st) => String(st.billstateid) === String(billstateid),
          )
        : undefined;
    return s ? s.billstate : billstateid;
  };

  const getCityName = (billcityid?: string, index?: number): string => {
    if (!billcityid) return "-";
    const c =
      index !== undefined
        ? cities[`city-${index}`]?.find(
            (ct) => String(ct.billcityid) === String(billcityid),
          )
        : undefined;
    return c ? c.billcity : billcityid;
  };

  const extractUniqueId = (slug: string): string => {
    const parts = slug.split("/");
    return parts[parts.length - 1];
  };

  const fetchAccreditation = async (): Promise<void> => {
    try {
      if (slug) {
        const uniqueID = extractUniqueId(slug);

        if (uniqueID.startsWith("IAAB")) {
          const response = await axios.get<ApiResponse<Accreditation>>(
            `${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 || "",
            }));
          }
        } else {
          const response = await axios.get<ApiResponse<Accreditation>>(
            `${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 || "",
            }));
          }
        }
      }
    } catch (error) {
      console.log("Association fetch error:", error);
      redirectTo404();
    }
  };

  const fetchAccreditation2 = async (): Promise<void> => {
    try {
      if (slug) {
        const response = await axios.get<ApiResponse<Accreditation>>(
          `${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: KeyLocation, 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: CaptchaResponse } = await getData(
        "captcha/generateCaptcha",
        {
          withCredentials: true,
        },
      );
      setCaptchaSvg(data?.captcha || "");
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchAllCountries();
    fetchCaptcha();
    fetchWebsite();
    fetchMemberPageData();

    fetchAccreditation().then(() => {
      if (!accreditation) {
        fetchAccreditation2();
      }
    });
  }, [slug]);

  useEffect(() => {
    if (typeof window !== "undefined" && accreditation?.uniqueID) {
      const safeUniqueID = accreditation.uniqueID.replace(/\//g, "-");
      const url = `https://iaabweb.work4node.in/associationmember/${safeUniqueID}`;
      setCurrentUrl(url);
    }
  }, [accreditation?.uniqueID]);

  const handleSubmit = async (
    e: React.FormEvent<HTMLFormElement>,
  ): Promise<void> => {
    e.preventDefault();

    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;
    }
    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;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.emailId)) {
      toast.error("Please enter a valid email address");
      return;
    }

    setLoading(true);
    try {
      const res: ApiResponse<any> = await postData("memberenquiry", formData, {
        withCredentials: true,
      });

      if (res?.success) {
        setFormData({
          accreditationId: accreditation?._id || "",
          name: "",
          contactNo: "",
          emailId: "",
          companyName: "",
          subject: "",
          memberenquiry: "",
          captcha: "",
          memberenquiryFrom: "Association Member",
        });
        toast.success(res?.message);
      } else {
        toast.error(res?.message);
      }
    } catch (error) {
      console.error(error);
      toast.error("Error submitting form");
    } finally {
      setLoading(false);
      fetchCaptcha();
    }
  };

  const getIconUrl = (iconPath: string): string => {
    if (typeof window !== "undefined") {
      return `${window.location.origin}${iconPath}`;
    }
    return iconPath;
  };

  const getFullName = (): string => {
    if (accreditation?.cFirstName && accreditation?.cLastName) {
      return `${accreditation.cFirstName} ${accreditation.cLastName}`;
    }
    return (
      accreditation?.cFirstName ||
      accreditation?.oFullName ||
      accreditation?.displayName ||
      "Organization"
    );
  };

  const getLogoUrl = (path?: string): string | null => {
    if (!path) return null;
    const cleanPath = String(path).replace(/\\/g, "/");
    if (cleanPath.startsWith("http")) return cleanPath;
    return `${BASE_URL2}${cleanPath}`;
  };

  const formatDate = (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";
    }
  };

  // Parse standards for roles
  const getParsedStandards = (): StandardItem[] => {
    if (!accreditation?.standards || !Array.isArray(accreditation.standards))
      return [];

    let finalArray: StandardItem[] = [];

    accreditation.standards.forEach((item: any) => {
      try {
        const parsed = typeof item === "string" ? JSON.parse(item) : item;
        if (Array.isArray(parsed)) {
          finalArray = [...finalArray, ...parsed];
        }
      } catch (err) {
        console.error("Standards parse error", err);
      }
    });

    return finalArray;
  };

  const standardsData = getParsedStandards();
  const roles = [
    ...new Set(
      standardsData
        .map((s: StandardItem) => s.glaApprovalStatus)
        .filter(Boolean),
    ),
  ];

  const maxVisible = 3;
  const visibleRoles = roles.slice(0, maxVisible);
  const remainingRolesCount = roles.length - maxVisible;

  if (!accreditation) return <Loading />;

  return (
    <>
      <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;
        }

        .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;
          color: rgba(3, 47, 78, 1);
          font-family: "Libre Baskerville", serif;
          font-weight: 700;
        }

        .profile-image {
          width: 100px !important;
          height: 100px !important;
          border-radius: 8px;
          overflow: hidden;
          background-color: #fff;
          border: 2px solid #e5e7eb;
        }

        .profile-initial {
          font-size: 48px !important;
          font-weight: 700;
          color: rgba(7, 59, 89, 1);
          background-color: #f0f4ff;
          font-family: "Plus Jakarta Sans", sans-serif;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
        }

        .role-title {
          font-size: 15px !important;
          margin-top: 5px !important;
          margin-bottom: 5px !important;
          color: rgba(3, 47, 78, 1);
          font-family: "Libre Baskerville", serif;
          font-weight: 700;
        }

        .detail-text {
          font-size: 13px !important;
          line-height: 1.4 !important;
          font-family: "Plus Jakarta Sans", sans-serif;
        }

        .org-logo {
          width: 90px !important;
          height: 90px !important;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .qr-container {
          padding: 11px !important;
          background-color: rgba(245, 224, 226, 0.3);
          border-radius: 10px;
          border: 2px solid rgba(245, 224, 226, 1);
        }

        .qr-code canvas {
          width: 110px !important;
          height: 110px !important;
        }

        .detail-row {
          gap: 8px !important;
          margin-bottom: 8px !important;
        }

        .right-section {
          gap: 16px !important;
          padding-top: 4px !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;
          }
        }
      `}</style>

      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4 md:px-8">
        <div className="mx-auto md:w-[100%] bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
          {/* Certificate Card - New Design */}
          <div className="bg-gradient-to-r from-blue-600 to-indigo-700 px-4 md:px-6 py-6 md:p-5 text-white">
            <div className="flex flex-col gap-6 items-center justify-between mobileONLy">
              {currentUrl && accreditation && (
                <div
                  className="certificate-card relative shadow-2xl"
                  style={{
                    overflowX: "auto",
                    padding: "0 16px",
                  }}
                >
                  {/* Content Container */}
                  <div className="card-content relative z-10 ">
                    {/* HEADER */}
                    <div className="text-center mb-6">
                      <h4 className="header-title">
                        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">
                            {accreditation.clientLogo ? (
                              <img
                                src={
                                  logoBase64 ||
                                  getLogoUrl(accreditation.clientLogo) ||
                                  ""
                                }
                                alt="Profile"
                                style={{
                                  width: "100%",
                                  height: "100%",
                                  objectFit: "cover",
                                }}
                                onError={(
                                  e: React.SyntheticEvent<HTMLImageElement>,
                                ) => {
                                  if (!logoBase64) {
                                    e.currentTarget.src =
                                      getLogoUrl(accreditation.clientLogo) ||
                                      "";
                                  }
                                }}
                              />
                            ) : (
                              <div className="profile-initial">
                                {getFullName().charAt(0)}
                              </div>
                            )}
                          </div>
                        </div>

                        {/* ROLE/TYPE */}
                        <div style={{ marginTop: "5px" }}>
                          <h2 className="role-title">
                            {roles.length > 0
                              ? `${visibleRoles.join(", ")}${remainingRolesCount > 0 ? ` +${remainingRolesCount} more` : ""}`
                              : accreditation.type
                                ? `${
                                    accreditation.type.charAt(0).toUpperCase() +
                                    accreditation.type.slice(1)
                                  } Member`
                                : "Association Member"}
                          </h2>
                        </div>

                        {/* USER DETAILS */}
                        <div className="space-y-2" style={{ marginTop: "5px" }}>
                          <div className="detail-row flex items-start gap-2">
                            <img
                              src={getIconUrl("/wpf_name.svg")}
                              alt="Organization Name"
                              className="detail-icon"
                              crossOrigin="anonymous"
                            />
                            <div className="detail-text">
                              <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 || "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"
                            />
                            <div className="detail-text">
                              <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"
                            />
                            <div className="detail-text">
                              <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"
                            />
                            <div className="detail-text">
                              <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"
                            />
                            <div className="detail-text">
                              <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
                                  ? formatDate(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="Status"
                              className="detail-icon"
                              crossOrigin="anonymous"
                            />
                            <div className="detail-text">
                              <span
                                style={{
                                  fontWeight: "600",
                                  color: "rgba(7, 59, 89, 1)",
                                }}
                              >
                                Certification Status:{" "}
                              </span>
                              <span
                                style={{
                                  color: accreditation.status
                                    ? "#28a745"
                                    : "#dc3545",
                                  fontWeight: "500",
                                }}
                              >
                                {accreditation.status ? "ACTIVE" : "INACTIVE"}
                              </span>
                            </div>
                          </div> */}
                        </div>
                      </div>

                      {/* RIGHT SECTION */}
                      <div className="right-section flex flex-col items-center justify-between">
                        {/* ORGANIZATION LOGO */}
                        {postImage && (
                          <div className="org-logo">
                            <img
                              src={postImageBase64 || postImage.CardImage || ""}
                              alt="Certificate Image"
                              style={{
                                maxWidth: "100%",
                                maxHeight: "100%",
                                objectFit: "contain",
                              }}
                              onError={(
                                e: React.SyntheticEvent<HTMLImageElement>,
                              ) => {
                                if (
                                  e.currentTarget.src === postImageBase64 &&
                                  postImage.CardImage
                                ) {
                                  e.currentTarget.src = postImage.CardImage;
                                }
                              }}
                            />
                          </div>
                        )}

                        {/* QR CODE */}
                        <div className="qr-container">
                          <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>
          </div>

          {/* Description */}
          <div className="p-6 md:p-5">
            {/* About Section */}
            {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>
            )}

            {/* Key Locations */}
            {accreditation.KeyLocation &&
              accreditation.KeyLocation.length > 0 && (
                <section className="mb-8">
                  <h2 className="text-lg font-semibold mb-3">
                    Key Locations ({accreditation.KeyLocation?.length})
                  </h2>
                  <div className="overflow-x-auto">
                    <table className="w-full">
                      <thead className="bg-gray-100">
                        <tr>
                          <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                            Country
                          </th>
                          <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                            State
                          </th>
                          <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                            City
                          </th>
                          <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                            Address
                          </th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-200">
                        {accreditation.KeyLocation?.map(
                          (loc: KeyLocation, idx: number) => (
                            <tr key={idx}>
                              <td className="px-4 py-3 text-sm text-gray-700">
                                {getCountryName(loc.country) || "Loading..."}
                              </td>
                              <td className="px-4 py-3 text-sm text-gray-700">
                                {getStateName(loc.state, idx) || "Loading..."}
                              </td>
                              <td className="px-4 py-3 text-sm text-gray-700">
                                {getCityName(loc.city, idx) || "Loading..."}
                              </td>
                              <td className="px-4 py-3 text-sm text-gray-700">
                                {loc.address}
                              </td>
                            </tr>
                          ),
                        )}
                      </tbody>
                    </table>
                  </div>
                </section>
              )}

            {/* Enquiry Form */}
            <div
              className="bg-gradient-to-r from-slate-50 to-blue-50 rounded-2xl p-4 border border-slate-200 mt-16"
              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: React.ChangeEvent<HTMLInputElement>) =>
                        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: React.ChangeEvent<HTMLInputElement>) =>
                        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: React.ChangeEvent<HTMLInputElement>) =>
                        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: React.ChangeEvent<HTMLInputElement>) =>
                        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: React.ChangeEvent<HTMLSelectElement>) =>
                      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: React.ChangeEvent<HTMLTextAreaElement>) =>
                      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: React.ChangeEvent<HTMLInputElement>) =>
                        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>
    </>
  );
}
