"use client";
import Image from "next/image";
import type React from "react";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { useState, useEffect } from "react";
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { QRCodeCanvas } from "qrcode.react";
import SafeHtmlRenderer from "../SafeHtmlRenderer";
import {
  RefreshCw,
  MapPin,
  Building2,
  Globe,
  Phone,
  Mail,
  User,
  MessageSquare,
  CheckCircle,
  XCircle,
  ExternalLink,
} from "lucide-react";
import useAxios from "@/hooks/useAxios";
import axios from "axios";
import { BASE_URL } from "@/Constant";
import Loading from "@/components/Loading/Loading";
import { toast } from "react-toastify";
import Loader from "../../components/Loader/Loader";

export default function InnerAbout({ slug }: any) {
  const pathname = usePathname();
  const [loading, setLoading] = useState(false);
  const searchParams = useSearchParams();
  const [currentUrl, setCurrentUrl] = useState("");
  const [captchaSvg, setCaptchaSvg] = useState("");
  const { postData, getData } = useAxios();
  const [message, setMessage] = useState<string>("");
  const [formData, setFormData] = useState({
    accreditationId: "",
    name: "",
    contactNo: "",
    emailId: "",
    companyName: "",
    subject: "",
    enquiry: "",
    captcha: "",
    enquiryFrom: "personal",
  });
  const [notFound, setNotFound] = useState(false);
  const router = useRouter();

  const redirectTo404 = () => {
    setNotFound(true);
    router.push("/404");
  };
  const [accreditation, setAccreditation] = useState<any>(null);
  const [accreditationID, setAccreditationID] = useState<any>(null);

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

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

  const getCountryName = (billcountryid: string) => {
    console.log("Looking for country ID:", billcountryid);
    console.log("Available countries:", countries);

    if (!billcountryid) return "-";

    const country = countries.find(
      (c) => String(c.billcountryid) === String(billcountryid),
    );

    console.log("Found country:", country);
    return country ? country.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 parseStandards = () => {
    try {
      if (accreditation?.standards && accreditation.standards.length > 0) {
        if (typeof accreditation.standards[0] === "string") {
          return JSON.parse(accreditation.standards[0]);
        }
        return accreditation.standards;
      }
      return [];
    } catch (error) {
      console.error("Error parsing standards:", error);
      return [];
    }
  };

  const parseCountryAllocation = () => {
    try {
      if (
        accreditation?.countryAllocation &&
        accreditation.countryAllocation.length > 0
      ) {
        const countryData = accreditation.countryAllocation[0];

        // अगर डेटा खाली स्ट्रिंग या whitespace है तो खाली array return करें
        if (typeof countryData === "string") {
          let cleanString = countryData.trim();

          // खाली या अमान्य डेटा के लिए check
          if (
            cleanString === "" ||
            cleanString === '""' ||
            cleanString === '""' ||
            cleanString === '\"\\\"\\\"\"' ||
            cleanString === '\\"\\"' ||
            cleanString === "[]" ||
            cleanString === "null"
          ) {
            return [];
          }

          // JSON strings को साफ़ करें
          if (cleanString.startsWith('"') && cleanString.endsWith('"')) {
            cleanString = cleanString.slice(1, -1);
          }

          cleanString = cleanString.replace(/\\"/g, '"');
          cleanString = cleanString.replace(/\\\\/g, "\\");

          try {
            const parsed = JSON.parse(cleanString);

            if (Array.isArray(parsed)) {
              // सभी खाली/अमान्य entries को filter करें
              return parsed
                .filter((item) => {
                  if (typeof item === "string") {
                    const trimmed = item.trim();
                    return (
                      trimmed.length > 0 &&
                      trimmed !== '""' &&
                      trimmed !== "null" &&
                      trimmed !== "undefined" &&
                      !trimmed.startsWith('\\"')
                    );
                  }
                  return false;
                })
                .map((item) => item.trim());
            } else if (typeof parsed === "string") {
              try {
                const innerParsed = JSON.parse(parsed);
                if (Array.isArray(innerParsed)) {
                  return innerParsed
                    .filter(
                      (item) =>
                        typeof item === "string" && item.trim().length > 0,
                    )
                    .map((item) => item.trim());
                }
              } catch {
                // अगर JSON parse नहीं होता, तो manual parsing करें
                const match = parsed.match(/\[(.*?)\]/);
                if (match) {
                  const countries = match[1]
                    .split(",")
                    .map((c) => c.trim().replace(/"/g, ""))
                    .filter((c) => c.length > 0);
                  return countries;
                }
                // सीधे स्ट्रिंग को check करें
                const trimmed = parsed.trim();
                if (trimmed.length > 0 && trimmed !== '""') {
                  return [trimmed];
                }
                return [];
              }
            }
          } catch (parseError) {
            // Regex-based fallback parsing
            const countryRegex =
              /"([^"]+)"|'([^']+)'|(\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b)/g;
            const matches = cleanString.match(countryRegex);
            if (matches) {
              const filtered = matches
                .map((match) =>
                  match.replace(/^"+|"+$/g, "").replace(/^'+|'+$/g, ""),
                )
                .filter(
                  (c) =>
                    c &&
                    c.length > 0 &&
                    c !== '""' &&
                    !c.includes("[") &&
                    !c.includes("]"),
                );
              return filtered.length > 0 ? filtered : [];
            }
            return [];
          }
        } else if (Array.isArray(countryData)) {
          // Array case में भी filter करें
          return countryData
            .filter((item) => {
              if (typeof item === "string") {
                const trimmed = item.trim();
                return (
                  trimmed.length > 0 &&
                  trimmed !== '""' &&
                  trimmed !== "null" &&
                  trimmed !== "undefined"
                );
              }
              return false;
            })
            .map((item) => item.trim());
        }
      }
      return []; // Default: खाली array return करें
    } catch (error) {
      console.error("Error parsing country allocation:", error);
      return [];
    }
  };

  const formatUniqueIDForURL = (uniqueID: string) => {
    return encodeURIComponent(uniqueID.replace(/\//g, "---"));
  };

  const fetchAccreditationID = async (abName: string) => {
    try {
      console.log("Fetching accreditation for AB ID:", abName);

      const response = await axios.get(
        `${BASE_URL}pcb/getPcbById?pcbId=${abName}`,
      );

      console.log("API Response:", response.data);

      if (response.data?.success && response.data.data) {
        // यहाँ data array नहीं है, object है!
        const acc = response.data.data;
        console.log("Setting accreditationID to:", acc);
        setAccreditationID(acc);
      } else {
        console.log("No accreditation data found");
        setAccreditationID(null); // Explicitly set to null
      }
    } catch (error: any) {
      console.error("Error fetching accreditation ID:", error);
      setAccreditationID(null); // Explicitly set to null on error
    }
  };

  const fetchAccreditation = async () => {
    try {
      if (slug) {
        console.log("Fetching accreditation for slug:", slug);
        const response = await axios.get(
          `${BASE_URL}personal/searchPersonalBySlug?slug=${slug}`,
        );

        if (response.data.success && response.data.data[0]) {
          const acc = response.data.data[0];
          console.log("Accreditation fetched:", acc);
          setAccreditation(acc);
          setFormData((prev) => ({ ...prev, accreditationId: acc._id }));

          // Call fetchAccreditationID after accreditation is set
          if (acc.abName) {
            console.log("Calling fetchAccreditationID with:", acc.abName);
            fetchAccreditationID(acc.abName);
          }

          acc?.KeyLocation?.forEach((loc: any, i: number) => {
            if (loc.country) fetchStates(loc.country, `state-${i}`);
            if (loc.state) fetchCities(loc.state, `city-${i}`);
          });
        } else {
          console.log("No accreditation found for slug:", slug);
          redirectTo404();
        }
      }
    } catch (error) {
      console.error("Error fetching accreditation:", error);
      redirectTo404();
    }
  };

  const fetchAccreditation2 = async () => {
    try {
      if (slug) {
        const response = await axios.get(
          `${BASE_URL}personal/searchPersonalBySlug2?slug=${slug}`,
        );
        const acc = response.data.data[0];
        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}`);
        });
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchAllCountries();
    fetchAccreditation();
    fetchAccreditation2();
    fetchCaptcha();
  }, []);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const params = searchParams?.toString();
      const url = `${window.location.origin}${pathname}${
        params ? `?${params}` : ""
      }`;
      setCurrentUrl(url);
    }
  }, [pathname, searchParams]);

  const fetchCaptcha = async () => {
    try {
      const { data }: any = await getData("captcha/generateCaptcha", {
        withCredentials: true,
      });
      setCaptchaSvg(data?.captcha);
    } catch (error) {
      console.log(error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name) {
      toast.error("Name is required");
      return;
    }
    if (!formData.contactNo) {
      toast.error("Contact number is required");
      return;
    }
    if (!formData.emailId) {
      toast.error("Email is required");
      return;
    }
    if (!formData.companyName) {
      toast.error("Company name is required");
      return;
    }
    if (!formData.subject) {
      toast.error("Subject is required");
      return;
    }
    if (!formData.enquiry) {
      toast.error("Enquiry is required");
      return;
    }
    if (!formData.captcha) {
      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("enquiry", formData, {
        withCredentials: true,
      });

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

  if (!accreditation) return <Loading />;

  const standards = parseStandards();
  const countryAllocation = parseCountryAllocation();

  const hasValidStandards =
    standards.length > 0 &&
    standards.some(
      (std: any) =>
        std.standardNumber ||
        std.glaLogoApprovalNumber ||
        std.glaApprovalStatus,
    );

  const hasOrganizationDescription =
    accreditation?.description?.trim().length > 0;

  const hasCountryAllocation = countryAllocation.length > 0;

  // Generate the link for accreditation body
  // const getAccreditationLink = () => {
  //   if (!accreditationID) return "#";
  //   if (accreditationID.uniqueID) {
  //     return `/personnelcertificationbody/${accreditationID.uniqueID}`;
  //   }
  //   return "#";
  // };
  const getAccreditationLink = () => {
    if (!accreditationID) return null;

    // यदि आपका route `/personnelcertificationbody/[uniqueID]` है
    return `${window.location.origin}/personalbody/${accreditationID.uniqueID}`;

    // या यदि query parameter के through जाना है
    // return `${window.location.origin}/personnelcertificationbody?id=${accreditationID._id}`;
  };

  const hasProfileDetails =
    accreditation.about?.trim() ||
    accreditation.qualification?.trim() ||
    accreditation.achivedTrainingCertificates?.trim() ||
    accreditation.workExperience?.trim() ||
    accreditation.auditingExperience?.trim() ||
    accreditation.consultancyExperience?.trim() ||
    accreditation.speciliedArea?.trim() ||
    accreditation.coreSkills?.trim() ||
    accreditation.keyAchivements?.trim() ||
    accreditation.anyOtherCrediencials?.trim();

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4 md:p-8">
      <div className="mx-auto md:w-[87%] bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
        <div className="bg-gradient-to-r from-blue-600 to-indigo-700 px-6  py-1 md:px-5 md:py-2 text-white">
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
            <div className="flex items-center gap-6 flex-wrap sm:flex-nowrap">
              <div className="w-24 h-24 relative bg-white  p-2 shadow-lg">
                {accreditation.logo ? (
                  <Image
                    src={`${BASE_URL}${accreditation.logo}`}
                    alt={accreditation.organisationName}
                    width={88}
                    height={88}
                    className="w-full h-full object-contain"
                    unoptimized={true}
                  />
                ) : (
                  <div className="w-full h-full bg-slate-100 flex items-center justify-center  text-slate-400 text-xs">
                    No Logo
                  </div>
                )}
              </div>

              <div>
                <h4 className="text-xl flex text-gray-900 font-bold mb-1">
                  {accreditation.organisationName}{" "}
                  {/* <div className="flex items-center px-3">
                    {" "}
                    {accreditation.isVerified ? (
                      <>
                        <CheckCircle className="w-4 h-4 text-green-400" />
                        <span className="text-sm text-green-300">Verified</span>
                      </>
                    ) : (
                      <>
                        <XCircle className="w-4 h-4 text-red-400" />
                        <span className="text-sm text-red-300">
                          Not Verified
                        </span>
                      </>
                    )}
                  </div> */}
                </h4>

                <p className="text-blue-100 text-lg mb-1">
                  <span
                    className={`
    px-3 py-1 rounded-full text-sm font-medium
    ${accreditation.certificateStatus === "Active" ? "bg-green-100 text-green-800" : ""}
    ${accreditation.certificateStatus === "Suspend" ? "bg-yellow-100 text-yellow-800" : ""}
    ${accreditation.certificateStatus === "Withdrawn" ? "bg-red-100 text-red-800" : ""}
    ${accreditation.certificateStatus === "Cancelled" ? "bg-gray-100 text-gray-800" : ""}
  `}
                  >
                    {accreditation.certificateStatus}
                  </span>
                </p>
                <div className="flex flex-col">
                  <p className="text-blue-100 text-lg mb-1">
                    {accreditation.Iagree === true && (
                      <span
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {accreditation.userEmail}
                      </span>
                    )}
                  </p>
                  <p className="text-blue-100 text-lg mb-1">
                    {accreditation.Iagree === true && (
                      <span
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {accreditation.phone}
                      </span>
                    )}
                  </p>
                </div>
              </div>
            </div>

            <div className="flex flex-row gap-3">
              {accreditation.glalogo && (
                <div className="w-24 h-24 relative bg-white p-2 shadow-lg">
                  <Image
                    src={`${BASE_URL}${accreditation.glalogo}`}
                    alt="GLA Logo"
                    width={88}
                    height={88}
                    className=" w-full h-full object-contain"
                    unoptimized={true}
                  />
                </div>
              )}
              {currentUrl && (
                <div className="text-center">
                  <QRCodeCanvas
                    value={currentUrl}
                    size={80}
                    level="H"
                    includeMargin={true}
                  />
                  <span className="text-sm text-slate-600 mt-2 block">
                    Scan QR Code
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="p-6 md:p-5">
          <section className="mb-8">
            <h2 className="text-xl font-bold text-slate-800 mb-3">
              Unique Identification Number{" "}
            </h2>
            <p
              className="bg-gray-100 mb-1 p-2 rounded-md text-blue-100 text-lg"
              ref={(el) => {
                if (el) el.style.setProperty("font-size", "14px", "important");
              }}
            >
              {accreditation.uniqueID}
            </p>
          </section>
          {hasValidStandards && (
            <section className="mb-8">
              <h2 className="text-xl font-bold text-slate-800 mb-4">
                Training Standard
              </h2>
              <div className="overflow-x-auto bg-slate-50 rounded-xl border border-slate-200">
                <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"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Name of Courses
                      </th>
                      <th
                        className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Status
                      </th>
                      <th
                        className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Certification Type
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {standards.map((standard: any, index: number) => (
                      <tr key={standard._id || index}>
                        <td
                          className="px-4 py-3 text-sm text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          {standard.standardNumber || "N/A"}
                        </td>

                        <td
                          className="px-4 py-3 text-sm text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          {standard.glaLogoApprovalNumber || "N/A"}
                        </td>
                        <td
                          className="px-4 py-3 text-sm text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          {standard.glaApprovalStatus || "N/A"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          )}
          {hasOrganizationDescription && (
            <section className="mb-8">
              <div className="flex items-center gap-3 mb-4">
                <h2 className="text-xl font-bold text-slate-800 mb-4">
                  Description
                </h2>
              </div>
              <div className="bg-slate-50 rounded-xl p-6 flex-wrap sm:flex-nowrap ">
                <p
                  className="text-slate-700 leading-relaxed text-justify text-base"
                  ref={(el) => {
                    if (el)
                      el.style.setProperty("font-size", "14px", "important");
                  }}
                >
                  {accreditation?.description}
                </p>
              </div>
            </section>
          )}
          {accreditation.KeyLocation?.length > 0 && (
            <section className="mb-7">
              <h2 className="text-xl font-bold text-slate-800 mb-4">
                Key Locations
              </h2>
              <div className="overflow-x-auto bg-slate-50 rounded-xl border border-slate-200">
                <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"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Address Type
                      </th>
                      <th
                        className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Address
                      </th>

                      <th
                        className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        Country
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {accreditation.KeyLocation.map(
                      (loc: any, index: number) => {
                        return (
                          <tr key={index}>
                            <td
                              className="px-4 py-3 text-sm text-gray-700 capitalize"
                              ref={(el) => {
                                if (el)
                                  el.style.setProperty(
                                    "font-size",
                                    "14px",
                                    "important",
                                  );
                              }}
                            >
                              {loc.registeredAddress?.replace("_", " ") ||
                                "N/A"}
                            </td>
                            <td
                              className="px-4 py-3 text-sm text-gray-700"
                              ref={(el) => {
                                if (el)
                                  el.style.setProperty(
                                    "font-size",
                                    "14px",
                                    "important",
                                  );
                              }}
                            >
                              {loc.address || "N/A"}
                            </td>
                            <td
                              className="px-4 py-3 text-sm text-gray-700"
                              ref={(el) => {
                                if (el)
                                  el.style.setProperty(
                                    "font-size",
                                    "14px",
                                    "important",
                                  );
                              }}
                            >
                              {getCountryName(loc.country)}
                            </td>
                          </tr>
                        );
                      },
                    )}
                  </tbody>
                </table>
              </div>
            </section>
          )}
          {hasCountryAllocation && countryAllocation.length > 0 && (
            <section className="mb-3">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2 mb-1">
                  Country Allocations
                </h2>
                <span className="text-sm text-slate-500 bg-slate-100 px-3 py-1 rounded-full">
                  {countryAllocation.length} Countries
                </span>
              </div>

              {countryAllocation.length <= 10 ? (
                <div className="flex flex-wrap gap-2">
                  {countryAllocation.map((country: string, index: number) => (
                    <span
                      key={index}
                      className="px-4 py-2 bg-blue-50 text-blue-700 rounded-lg border border-blue-100 text-sm font-medium hover:bg-blue-100 transition-colors"
                      title={country}
                    >
                      {country}
                    </span>
                  ))}
                </div>
              ) : (
                <>
                  <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                    {countryAllocation
                      .slice(0, 8)
                      .map((country: string, index: number) => (
                        <div
                          key={index}
                          className="p-3 bg-white border border-slate-200 rounded-lg hover:border-blue-300 transition-colors"
                        >
                          <div className="flex items-center">
                            <div className="w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center mr-2 flex-shrink-0">
                              <span className="text-blue-600 font-bold text-xs">
                                {index + 1}
                              </span>
                            </div>
                            <span
                              className="text-slate-700 text-sm truncate"
                              title={country}
                            >
                              {country}
                            </span>
                          </div>
                        </div>
                      ))}
                  </div>

                  <div className="mt-4 text-center">
                    <button
                      onClick={() => {
                        const message = `Total ${
                          countryAllocation.length
                        } Countries:\n\n${countryAllocation.join("\n")}`;
                        alert(message);
                      }}
                      className="text-blue-600 hover:text-blue-800 text-sm font-medium px-4 py-2 border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors"
                    >
                      View All {countryAllocation.length} Countries
                    </button>
                  </div>
                </>
              )}
            </section>
          )}
          {/* IAAB Standard Procedures Section */}
          <section className="mb-7 mt-9">
            <h2 className="text-xl font-bold text-slate-800 mb-4">
              Personnel Certification Body
            </h2>
            <div className="overflow-x-auto bg-slate-50 rounded-xl border border-slate-200">
              <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"
                      ref={(el) => {
                        if (el)
                          el.style.setProperty(
                            "font-size",
                            "14px",
                            "important",
                          );
                      }}
                    >
                      Organisation Name
                    </th>
                    <th
                      className="px-4 py-3 text-left text-sm font-semibold text-gray-700"
                      ref={(el) => {
                        if (el)
                          el.style.setProperty(
                            "font-size",
                            "14px",
                            "important",
                          );
                      }}
                    >
                      Link
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {accreditationID === undefined ? (
                    // Loading state
                    <tr>
                      <td
                        className="px-4 py-3 text-sm text-gray-700"
                        colSpan={2}
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        <div className="flex items-center justify-center py-4">
                          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
                          <span className="ml-2 text-gray-500">
                            Loading accreditation details...
                          </span>
                        </div>
                      </td>
                    </tr>
                  ) : accreditationID === null ? (
                    // Error or no data state
                    <tr>
                      <td
                        className="px-4 py-3 text-sm text-gray-700"
                        colSpan={2}
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        <div className="flex items-center justify-center py-4">
                          <span className="text-gray-500">
                            Accreditation details not available
                          </span>
                        </div>
                      </td>
                    </tr>
                  ) : (
                    // Success state
                    <tr>
                      <td
                        className="px-4 py-3 text-sm text-gray-700 capitalize"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {accreditationID.organisationName || "N/A"}
                      </td>
                      <td
                        className="px-4 py-3 text-sm text-gray-700"
                        ref={(el) => {
                          if (el)
                            el.style.setProperty(
                              "font-size",
                              "14px",
                              "important",
                            );
                        }}
                      >
                        {accreditationID.organisationName ? (
                          <a
                            href={`/personnelcertificationbody/${formatUniqueIDForURL(
                              accreditationID.slug,
                            )}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center bg-btn-ob gap-1 px-3 py-1.5 bg-blue-50 text-blue-700 hover:bg-blue-100 border border-blue-200 rounded-lg transition-colors text-sm font-medium"
                          >
                            View Details
                            <ExternalLink className="w-3 h-3" />
                          </a>
                        ) : (
                          "N/A"
                        )}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </section>

          {hasProfileDetails && (
            <section className="mb-8">
              <div className="flex items-center gap-3 mb-2 mt-2">
                <h2 className="text-xl font-bold text-slate-800 mt-3 mb-2">
                  Profile Details
                </h2>
              </div>

              <div className="bg-gradient-to-br from-slate-50 to-blue-50 rounded-xl border border-slate-200 p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {/* Left Column */}

                  {/* About Section */}
                  {accreditation.about && accreditation.about.trim() !== "" && (
                    <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                      <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                        <User className="w-4  text-blue-600" />
                        About
                      </h3>
                      <p className="text-slate-700 leading-relaxed text-justify">
                        {accreditation.about}
                      </p>
                    </div>
                  )}

                  {/* Core Skills */}
                  {accreditation.coreSkills &&
                    accreditation.coreSkills.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">⚡</span>
                          Core Skills
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.coreSkills}
                        </p>
                      </div>
                    )}

                  {/* Key Achievements */}
                  {accreditation.keyAchivements &&
                    accreditation.keyAchivements.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">🏆</span>
                          Key Achievements
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.keyAchivements}
                        </p>
                      </div>
                    )}

                  {/* Consultancy Experience */}
                  {accreditation.consultancyExperience &&
                    accreditation.consultancyExperience.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">💼</span>
                          Consultancy Experience
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.consultancyExperience}
                        </p>
                      </div>
                    )}
                  {/* Qualification Section */}
                  {accreditation.qualification &&
                    accreditation.qualification.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">🎓</span>
                          Qualification
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.qualification}
                        </p>
                      </div>
                    )}

                  {/* Work Experience */}
                  {accreditation.workExperience &&
                    accreditation.workExperience.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">📈</span>
                          Work Experience
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.workExperience}
                        </p>
                      </div>
                    )}

                  {/* Achieved Training Certificates */}
                  {accreditation.achivedTrainingCertificates &&
                    accreditation.achivedTrainingCertificates.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">📜</span>
                          Achieved Training Certificates
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.achivedTrainingCertificates}
                        </p>
                      </div>
                    )}

                  {/* Auditing Experience */}
                  {accreditation.auditingExperience &&
                    accreditation.auditingExperience.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">🔍</span>
                          Auditing Experience
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.auditingExperience}
                        </p>
                      </div>
                    )}

                  {/* Specialized Area */}
                  {accreditation.speciliedArea &&
                    accreditation.speciliedArea.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">🎯</span>
                          Specialized Area
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.speciliedArea}
                        </p>
                      </div>
                    )}

                  {/* Other Credentials */}
                  {accreditation.anyOtherCrediencials &&
                    accreditation.anyOtherCrediencials.trim() !== "" && (
                      <div className="bg-white p-4 rounded-lg border border-slate-100 shadow-sm">
                        <h3 className="text-sm font-semibold text-slate-600 mb-2 flex items-center gap-2">
                          <span className="w-4  text-blue-600">📋</span>
                          Other Credentials
                        </h3>
                        <p className="text-slate-700 leading-relaxed text-justify">
                          {accreditation.anyOtherCrediencials}
                        </p>
                      </div>
                    )}
                </div>
              </div>
            </section>
          )}
          <div
            className="bg-gradient-to-r from-slate-50 to-blue-50 rounded-2xl p-4 border border-slate-200 mt-24"
            style={{ backgroundColor: "beige" }}
          >
            <h2 className="text-xl font-bold text-slate-800 mb-4">
              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  text-blue-600" />
                    Name <span className="text-red-500 font-bold">*</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  text-blue-600" />
                    Email <span className="text-red-500 font-bold">*</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  text-blue-600" />
                    Phone <span className="text-red-500 font-bold">*</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  text-blue-600" />
                    Company <span className="text-red-500 font-bold">*</span>
                  </label>
                  <input
                    type="text"
                    id="companyName"
                    placeholder="Enter company 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.companyName}
                    onChange={(e) =>
                      setFormData({ ...formData, companyName: e.target.value })
                    }
                    required
                  />
                </div>
              </div>

              <div>
                <label
                  htmlFor="subject"
                  className="block text-sm font-medium text-slate-700 mb-1"
                >
                  Subject <span className="text-red-500 font-bold">*</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="enquiry"
                  className="flex items-center gap-2 text-sm font-medium text-slate-700 mb-1"
                >
                  <MessageSquare className="w-4  text-blue-600" />
                  Enquiry Details{" "}
                  <span className="text-red-500 font-bold">*</span>
                </label>
                <textarea
                  id="enquiry"
                  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.enquiry}
                  onChange={(e) =>
                    setFormData({ ...formData, enquiry: 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 font-bold">*</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>
          <ToastContainer />
        </div>
      </div>
    </div>
  );
}
