"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 { 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 "../Loader/Loader";

export default function InnerAbout({ slug }: any) {
  const [formData, setFormData] = useState({
    accreditationId: "",
    name: "",
    contactNo: "",
    emailId: "",
    companyName: "",
    subject: "",
    memberenquiry: "",
    captcha: "",
    memberenquiryFrom: "Professional Member",
  });

  const [accreditation, setAccreditation] = useState<any>(null);
  const [captchaSvg, setCaptchaSvg] = useState("");
  const [loading, setLoading] = useState(false);
  const [currentUrl, setCurrentUrl] = useState("");
  const [websiteData, setWebsiteData] = useState(null);
  const [isDownloading, setIsDownloading] = useState(false);
  const cardRef = useRef<HTMLDivElement>(null);

  const [countries, setCountries] = useState<any[]>([]);
  const [states, setStates] = useState<Record<string, any[]>>({});
  const [cities, setCities] = useState<Record<string, any[]>>({});
  const [postImage, setPostImage] = useState(null);
  const [postImageBase64, setPostImageBase64] = useState(null);
  const [logoBase64, setLogoBase64] = useState(null);

  const { postData, getData } = useAxios();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [notFound, setNotFound] = useState(false);
  const router = useRouter();

  const redirectTo404 = () => {
    setNotFound(true);
    router.push("/404");
  };

  const fetchAllCountries = async () => {
    try {
      const res: any = 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) => {
    try {
      const res: any = 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) => {
    try {
      const res: any = 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) => {
    if (!billcountryid) return "-";
    const c = countries.find(
      (c) => String(c.billcountryid) === String(billcountryid),
    );
    return c ? c.billcountry : billcountryid;
  };

  const getStateName = (billstateid: string, index: number) => {
    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) => {
    if (!billcityid) return "-";
    const c = cities[`city-${index}`]?.find(
      (ct) => String(ct.billcityid) === String(billcityid),
    );
    return c ? c.billcity : billcityid;
  };

  const extractUniqueId = (slug: string) => {
    const parts = slug.split("/");
    return parts[parts.length - 1];
  };

  // Fetch website data
  const fetchWebsite = async () => {
    try {
      const res = await axios.get(
        `${BASE_URL}website/getWebsiteById?websiteId=66e3e5bfcdfd3a17049f0279`,
      );
      setWebsiteData(res?.data?.data);
    } catch (err) {
      console.error("Website fetch error", err);
    }
  };

  // Fetch member page data for card image
  const fetchMemberPageData = async () => {
    try {
      const res = await axios.get(
        `${BASE_URL}memberPageData/67c94e6d2e7e85a1c9c721fc`,
      );

      if (res?.data?.success && res?.data?.data) {
        setPostImage(res.data.data);

        // Handle CardImage if it exists
        if (res.data.data.CardImage) {
          const formattedPath = res.data.data.CardImage.replace(/\\/g, "/");
          const filename = formattedPath.split("/").pop();

          try {
            const imgRes = await axios.get(
              `${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);
    }
  };

  const fetchAccreditation = async () => {
    try {
      if (slug) {
        const uniqueID = extractUniqueId(slug);

        if (uniqueID.startsWith("IAAB")) {
          const response = await axios.get(
            `${BASE_URL}association-member/searchASSBySlug?uniqueId=${uniqueID}`,
          );

          if (response.data.success) {
            const acc = response.data.data;
            setAccreditation(acc);
            setFormData((prev) => ({
              ...prev,
              accreditationId: acc._id || "",
            }));

            // Convert logo to base64
            if (acc.profilelogo) {
              const filename = acc.profilelogo.split("/").pop();
              try {
                const imgRes = await axios.get(
                  `${BASE_URL}image-base64/${filename}`,
                );
                if (imgRes.data?.image) {
                  setLogoBase64(imgRes.data.image);
                }
              } catch (err) {
                console.error("Logo fetch error", err);
              }
            }
          }
        } else {
          const response = await axios.get(
            `${BASE_URL}association-member/searchASSBySlug?slug=${slug}`,
          );

          if (response.data.success) {
            const acc = response.data.data;
            setAccreditation(acc);
            setFormData((prev) => ({
              ...prev,
              accreditationId: acc._id || "",
            }));

            // Convert logo to base64
            if (acc.profilelogo) {
              const filename = acc.profilelogo.split("/").pop();
              try {
                const imgRes = await axios.get(
                  `${BASE_URL}image-base64/${filename}`,
                );
                if (imgRes.data?.image) {
                  setLogoBase64(imgRes.data.image);
                }
              } catch (err) {
                console.error("Logo fetch error", err);
              }
            }
          }
        }
      }
    } catch (error) {
      console.log("Association fetch error:", error);
      redirectTo404();
    }
  };

  const fetchAccreditation2 = async () => {
    try {
      if (slug) {
        const response = await axios.get(
          `${BASE_URL}cb/searchCbBySlug2?slug=${slug}`,
        );

        if (response.data.success) {
          const acc = response.data.data;
          setAccreditation(acc);
          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}`);
          });

          // Convert logo to base64
          if (acc.profilelogo) {
            const filename = acc.profilelogo.split("/").pop();
            try {
              const imgRes = await axios.get(
                `${BASE_URL}image-base64/${filename}`,
              );
              if (imgRes.data?.image) {
                setLogoBase64(imgRes.data.image);
              }
            } catch (err) {
              console.error("Logo fetch error", err);
            }
          }
        }
      }
    } catch (error) {
      console.log("CB fetch error:", error);
    }
  };

  const fetchCaptcha = async () => {
    try {
      const { data }: any = await getData("captcha/generateCaptcha", {
        withCredentials: true,
      });
      setCaptchaSvg(data?.captcha);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchAllCountries();
    fetchCaptcha();
    fetchWebsite();
    fetchMemberPageData();

    fetchAccreditation().then(() => {
      if (!accreditation) {
        fetchAccreditation2();
      }
    });

    // Set viewport for desktop
    // if (typeof window !== "undefined") {
    //   const viewport = document.querySelector('meta[name="viewport"]');
    //   if (viewport) {
    //     viewport.setAttribute(
    //       "content",
    //       "width=1024, initial-scale=0.5, user-scalable=yes",
    //     );
    //   }
    // }
  }, [slug]);

  useEffect(() => {
    if (typeof window !== "undefined" && accreditation?.uniqueID) {
      const safeUniqueID = accreditation.uniqueID?.replace(/\//g, "-");
      const url = `https://iaabweb.work4node.in/professionalmembers/${safeUniqueID}`;
      setCurrentUrl(url);
    }
  }, [accreditation]);

  const handleSubmit = async (e: React.FormEvent) => {
    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: any = await postData("memberenquiry", formData, {
        withCredentials: true,
      });

      if (res?.success) {
        setFormData({
          accreditationId: accreditation?._id || "",
          name: "",
          contactNo: "",
          emailId: "",
          companyName: "",
          subject: "",
          memberenquiry: "",
          captcha: "",
          memberenquiryFrom: "Professional 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 downloadCard = async () => {
    if (!cardRef.current || isDownloading) return;
    setIsDownloading(true);

    try {
      await document.fonts.ready;

      const element = cardRef.current;
      const images = element.querySelectorAll("img");
      const originalSrcs = [];

      // Store original srcs and replace with base64 if available
      images.forEach((img, index) => {
        originalSrcs[index] = img.src;

        // Replace with base64 if available
        if (img.alt === "Profile" && logoBase64) {
          img.src = logoBase64;
        } else if (img.alt === "Certificate Image" && postImageBase64) {
          img.src = postImageBase64;
        }
      });

      // Wait a bit for images to load
      await new Promise((resolve) => setTimeout(resolve, 500));

      const desktopWidth = 616;
      const desktopHeight = 452;
      const currentWidth = element.offsetWidth;
      const currentHeight = element.offsetHeight;

      // Calculate scale factor
      const scaleX = desktopWidth / currentWidth;
      const scaleY = desktopHeight / currentHeight;
      const scale = Math.max(scaleX, scaleY);

      const dataUrl = await domToPng(element, {
        quality: 1,
        scale: scale,
        width: desktopWidth,
        height: desktopHeight,
        style: {
          margin: "0",
          padding: "0",
        },
      });

      // Restore original image sources
      images.forEach((img, index) => {
        img.src = originalSrcs[index];
      });

      const link = document.createElement("a");
      link.href = dataUrl;
      link.download = `IAAB-Certificate-${accreditation?.uniqueID || "certificate"}.png`;
      link.click();
    } catch (err) {
      console.error("Download failed", err);
      toast.error("Download failed. Please try again.");
    } finally {
      setIsDownloading(false);
    }
  };

  const getIconUrl = (iconPath: string) => {
    if (typeof window !== "undefined") {
      return `${window.location.origin}${iconPath}`;
    }
    return iconPath;
  };

  const getFullName = () => {
    if (accreditation?.cFirstName && accreditation?.cLastName) {
      return `${accreditation.cFirstName} ${accreditation.cLastName}`;
    }
    return (
      accreditation?.cFirstName ||
      accreditation?.oFullName ||
      accreditation?.displayName ||
      "Organization"
    );
  };

  const getLogoUrl = (path: string) => {
    if (!path) return null;
    const cleanPath = String(path).replace(/\\/g, "/");
    if (cleanPath.startsWith("http")) return cleanPath;
    return `${BASE_URL2}${cleanPath}`;
  };

  // Parse standards for roles and courses
  const getParsedStandards = () => {
    if (!accreditation?.standards || !Array.isArray(accreditation.standards))
      return [];

    let finalArray = [];

    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();

  // Roles (glaApprovalStatus)
  const roles = [
    ...new Set(
      standardsData.map((s: any) => s.glaApprovalStatus).filter(Boolean),
    ),
  ];

  // Courses (glaLogoApprovalNumber)
  const courses = [
    ...new Set(
      standardsData.map((s: any) => s.glaLogoApprovalNumber).filter(Boolean),
    ),
  ];

  const maxVisible = 5;
  const visibleRoles = roles.slice(0, maxVisible);
  const remainingRolesCount = roles.length - maxVisible;
  const visibleCourses = courses.slice(0, maxVisible);
  const remainingCoursesCount = courses.length - maxVisible;

  const formatDate = (dateString: 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) => {
        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";
    }
  };

  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("/smallFrame.png") !important;
          background-size: cover !important;
          background-position: center !important;
          background-repeat: no-repeat !important;
          width: 616px !important;
          height: 349px !important;
          min-width: 616px !important;
          min-height: 349px !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;
        }
        @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;
          }
        }
        .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;
          width: 440px !important;
        }

        .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;
        }

        .courses-section {
          margin-top: 5px !important;
          padding: 6px !important;
          border-radius: 8px;
          background-color: #fef5f8;
          border: 1px solid #eecab3;
          width: 88% !important;
        }

        .courses-title {
          font-size: 13px !important;
          font-weight: 700;
          color: rgba(7, 59, 89, 1);
          font-family: "Plus Jakarta Sans", sans-serif;
        }

        .courses-text {
          font-size: 10px !important;
          line-height: 1.5;
          color: rgba(7, 59, 89, 1);
          font-family: "Plus Jakarta Sans", sans-serif;
          font-weight: 400;
          margin-left: 26px !important;
          width: 90% !important;
        }

        .detail-row {
          gap: 8px !important;
          margin-bottom: 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">
        <div className="mx-auto md:w-[100%] bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
          {/* Certificate Card - Download Button */}
          <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">
              {/* <div className="flex justify-center mb-6 sticky top-4 z-50">
                <button
                  onClick={downloadCard}
                  disabled={isDownloading}
                  className="rounded-lg px-8 py-3 font-semibold shadow-lg text-white transition-all hover:shadow-xl disabled:opacity-50"
                  style={{
                    background:
                      "linear-gradient(135deg, #B8860B 0%, #8B6914 100%)",
                    fontFamily: "'Plus Jakarta Sans', sans-serif",
                    fontSize: "16px",
                  }}
                >
                  {isDownloading ? "Downloading..." : "Download Certificate"}
                </button>
              </div> */}

              {currentUrl && accreditation && (
                <div
                  ref={cardRef}
                  className="certificate-card relative shadow-2xl overflow-hidden"
                  style={{
                    width: "616px",
                    height: "452px",
                    minWidth: "616px",
                    minHeight: "452px",
                    backgroundImage: "url('/smallFrame.png')",
                    backgroundSize: "cover",
                    backgroundPosition: "center",
                    backgroundRepeat: "no-repeat",
                  }}
                >
                  {/* Content Container */}
                  <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.profilelogo ? (
                              <img
                                src={
                                  logoBase64 ||
                                  getLogoUrl(accreditation.profilelogo)
                                }
                                alt="Profile"
                                style={{
                                  width: "100%",
                                  height: "100%",
                                  objectFit: "cover",
                                }}
                                onError={(e) => {
                                  console.log(
                                    "Profile image error, using fallback",
                                  );
                                  if (!logoBase64) {
                                    e.currentTarget.src =
                                      getLogoUrl(accreditation.profilelogo) ||
                                      "";
                                  }
                                }}
                              />
                            ) : (
                              <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",
                            }}
                          >
                            {roles.length > 0
                              ? `${visibleRoles.join(", ")}${remainingRolesCount > 0 ? ` +${remainingRolesCount} more` : ""}`
                              : accreditation.type
                                ? `${
                                    accreditation.type.charAt(0).toUpperCase() +
                                    accreditation.type.slice(1)
                                  } Member`
                                : "Professional 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)",
                                }}
                              >
                                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.email || "N/A"}
                              </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)",
                                }}
                              >
                                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>
                      </div>

                      {/* RIGHT SECTION */}
                      <div
                        className="right-section"
                        style={{
                          display: "flex",
                          flexDirection: "column",
                          alignItems: "center",
                          justifyContent: "space-between",
                          gap: "16px",
                          paddingTop: "4px",
                        }}
                      >
                        {/* ORGANIZATION LOGO - CERTIFICATE IMAGE */}
                        {postImage && (
                          <div
                            className="org-logo"
                            style={{
                              width: "90px",
                              height: "90px",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                          >
                            <img
                              src={postImageBase64 || postImage}
                              style={{
                                maxWidth: "100%",
                                maxHeight: "100%",
                                objectFit: "contain",
                              }}
                              alt="Certificate Image"
                              onError={(e) => {
                                console.log(
                                  "Post image error, trying fallback URL",
                                );
                                if (
                                  e.currentTarget.src === postImageBase64 &&
                                  postImage
                                ) {
                                  e.currentTarget.src = postImage;
                                }
                              }}
                            />
                          </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>

                    {/* COURSES SECTION */}
                    {courses.length > 0 && (
                      <div
                        className="courses-section"
                        style={{
                          marginTop: "5px",
                          padding: "6px",
                          borderRadius: "8px",
                          backgroundColor: "#FEF5F8",
                          border: "1px solid #EECAB3",
                          width: "88%",
                        }}
                      >
                        <div className="flex items-start gap-2 mb-0">
                          <img
                            src={getIconUrl("/clarity_certificate-solid.svg")}
                            alt="Courses"
                            className="detail-icon"
                            crossOrigin="anonymous"
                            style={{ marginTop: "0px" }}
                          />
                          <h3
                            className="courses-title"
                            style={{
                              fontWeight: "700",
                              fontSize: "13px",
                              color: "rgba(7, 59, 89, 1)",
                              fontFamily: "'Plus Jakarta Sans', sans-serif",
                            }}
                          >
                            Name Courses:
                          </h3>
                        </div>
                        <p
                          className="courses-text"
                          style={{
                            fontSize: "10px",
                            lineHeight: "1.5",
                            color: "rgba(7, 59, 89, 1)",
                            fontFamily: "'Plus Jakarta Sans', sans-serif",
                            fontWeight: "400",
                            marginBottom: "0px",
                            marginLeft: "26px",
                            marginTop: "0px",
                            width: "90%",
                          }}
                        >
                          {courses.length > 0
                            ? `${visibleCourses.join(", ")}${remainingCoursesCount > 0 ? ` +${remainingCoursesCount} more` : ""}`
                            : "No Courses Available"}
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Description */}
          <div className="p-6 md:p-5">
            {/* About Section */}
            {accreditation.expertise && (
              <section className="mb-8">
                <h2 className="text-xl font-bold text-slate-800 mb-2">
                  Your Expertise in which sector
                </h2>
                <div className="bg-slate-50 rounded-xl p-6 flex-wrap sm:flex-nowrap">
                  <p className="text-slate-700">{accreditation.expertise}</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: any, 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) =>
                        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>
    </>
  );
}
