"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: "pcb",
  });
  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 [];
    }
  };

  // Replace the parseCountryAllocation function with this:
  // Simple but powerful parser
  const parseCountryAllocation = () => {
    try {
      if (
        !accreditation?.countryAllocation ||
        accreditation.countryAllocation.length === 0
      ) {
        return [];
      }

      let data = accreditation.countryAllocation[0];
      console.log("Raw:", data);

      // Step 1: Keep parsing until we can't parse anymore
      let current = data;
      let depth = 0;
      const MAX_DEPTH = 10;

      while (depth < MAX_DEPTH) {
        try {
          const parsed = JSON.parse(current);

          // If we got an array of strings that look like country names
          if (
            Array.isArray(parsed) &&
            parsed.every(
              (item) =>
                typeof item === "string" &&
                !item.includes("[") &&
                !item.includes("\\"),
            )
          ) {
            return parsed.filter((item) => item.trim().length > 0);
          }

          // If we got an array but it's still encoded
          if (
            Array.isArray(parsed) &&
            parsed.length === 1 &&
            typeof parsed[0] === "string"
          ) {
            current = parsed[0];
          }
          // If we got a string
          else if (typeof parsed === "string") {
            current = parsed;
          }
          // If we got something else
          else {
            return Array.isArray(parsed) ? parsed : [];
          }
        } catch (e) {
          // Parsing failed, break
          break;
        }
        depth++;
      }

      // Step 2: Manual extraction using regex
      const match = data.match(/[A-Za-z\s]+/g);
      if (match) {
        return match.map((m) => m.trim()).filter((m) => m.length > 2); // Only keep words longer than 2 chars
      }

      return [];
    } catch (e) {
      console.error("Parse error:", e);
      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}ab/getAbById?abId=${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}pcb/searchPcbBySlug?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}pcb/searchPcbBySlug2?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: "pcb",
        });
        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;

  // Format full name from firstName and lastName
  const getFullName = () => {
    const firstName = accreditation?.firstName || "";
    const lastName = accreditation?.lastName || "";

    if (firstName || lastName) {
      return `${firstName} ${lastName}`.trim();
    }
    return null;
  };

  const fullName = getFullName();
  const hasContactInfo =
    fullName ||
    accreditation?.phone ||
    accreditation?.companyWebsite ||
    accreditation?.position;

  // const getCertificateBadge = (status: string) => {
  //   if (!status) return null;

  //   const baseStyle =
  //     "px-3 py-1 text-xs font-semibold rounded-full inline-block mt-2";

  //   switch (status.toLowerCase()) {
  //     case "Active":
  //       return (
  //         <span className={`${baseStyle} bg-green-100 text-green-300`}>
  //           Active
  //         </span>
  //       );

  //     case "Suspended":
  //       return (
  //         <span className={`${baseStyle} bg-yellow-100 text-yellow-700`}>
  //           Suspended
  //         </span>
  //       );

  //     case "Withdrawn":
  //       return (
  //         <span className={`${baseStyle} bg-orange-100 text-orange-700`}>
  //           Withdrawn
  //         </span>
  //       );

  //     case "Cancelled":
  //       return (
  //         <span className={`${baseStyle} bg-red-100 text-red-700`}>
  //           Cancelled
  //         </span>
  //       );

  //     default:
  //       return (
  //         <span className={`${baseStyle} bg-gray-100 text-gray-700`}>
  //           {status}
  //         </span>
  //       );
  //   }
  // };

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

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

    // या यदि query parameter के through जाना है
    // return `${window.location.origin}/accreditationbody?id=${accreditationID._id}`;
  };
  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=" contents sm:flex-nowrap">
              <div className="flex gap-4 items-center">
                {" "}
                <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}{" "}
                  </h4>
                  <div className="flex items-center">
                    {" "}
                    {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>
                  {/* {getCertificateBadge(accreditation?.certificateStatus)} */}
                  <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>{accreditation.userEmail}</span>
                      )}
                    </p>
                    <p className="text-blue-100 text-lg mb-1">
                      {accreditation.Iagree === true && (
                        <span>{accreditation.phone}</span>
                      )}
                    </p>
                    {/* <p className="text-blue-100 text-lg mb-1">
                  {accreditation.uniqueID}
                </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="">
            <section className="mb-8 mt-4">
              <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>

            {hasContactInfo && (
              <section className="mb-8">
                <h2 className="text-xl font-bold text-slate-800 mb-4 flex items-center gap-2">
                  Point of Contact
                </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
                        </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",
                              );
                          }}
                        >
                          Email Id
                        </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",
                              );
                          }}
                        >
                          Phone
                        </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",
                              );
                          }}
                        >
                          Website
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      <tr>
                        <td
                          className="px-4 py-3 text-sm text-gray-700"
                          ref={(el) => {
                            if (el)
                              el.style.setProperty(
                                "font-size",
                                "14px",
                                "important",
                              );
                          }}
                        >
                          {fullName || "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",
                              );
                          }}
                        >
                          {accreditation?.userEmail || "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",
                              );
                          }}
                        >
                          {accreditation?.phone || "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",
                              );
                          }}
                        >
                          {accreditation?.companyWebsite || "N/A"}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </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="rounded-xl p-3 flex-wrap sm:flex-nowrap bg-gray-100 ">
                  <p className="text-slate-700 leading-relaxed text-base">
                    {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 && (
              <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-black  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">
                Accreditation 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={`/accreditationbody/${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>

            <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 h-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 text-black 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 font-bold">*</span>
                    </label>
                    <input
                      type="email"
                      id="emailId"
                      placeholder="Enter email address"
                      className="w-full px-2 py-2 border text-black 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 font-bold">*</span>
                    </label>
                    <input
                      type="text"
                      id="contactNo"
                      placeholder="Enter contact number"
                      className="w-full px-2 py-2 border text-black 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 <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 text-black 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 text-black 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 h-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 text-black 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 text-black 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 text-black 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>
    </div>
  );
}
