import React from "react";
import { FindKineticProps, ThemeKey } from "./types";

import { Link } from "@shared/components/link";
import { Text } from "@shared/components/text";
import { NextImage } from "@shared/next";

export const FindKinetic: React.FC<FindKineticProps> = ({
  background = "white",
  description,
  enableHeading,
  image,
  list = [],
  localPathPrefix = "/local",
  subTitle,
  title,
  color = "dark",
  maxWidth = true,
  addTrailingSlash = false,
}) => {
  const bgColorClasses: Record<ThemeKey, string> = {
    blue: "bg-[#07B2E2]",
    green: "bg-[#26B170]",
    yellow: "bg-[#F5FF1E]",
    purple: "bg-[#931D69]",
    white: "bg-white",
    navy: "bg-[#00002D]",
  };
  // Trim leading/trailing slashes without a regex to avoid ReDoS on long
  // runs of "/" (CodeQL: polynomial regular expression on uncontrolled data).
  const trimSlashes = (value: string) => {
    let start = 0;
    let end = value.length;
    while (start < end && value.charCodeAt(start) === 47 /* "/" */) start += 1;
    while (end > start && value.charCodeAt(end - 1) === 47 /* "/" */) end -= 1;
    return value.slice(start, end);
  };
  const cleanedLocalPathPrefix = trimSlashes(localPathPrefix ?? "");
  const normalizedLocalPathPrefix = cleanedLocalPathPrefix
    ? `/${cleanedLocalPathPrefix}`
    : "";

  const getLocationHref = (code: string) =>
    `${normalizedLocalPathPrefix}/${code.toLowerCase()}${addTrailingSlash ? "/" : ""}`;

  return (
    <div
      className={`${bgColorClasses[background]} component-container overflow-hidden ${color == "dark" ? "text-text" : "text-white"}`}
    >
      <div
        className={`${maxWidth ? "max-w-120 xl:mx-auto" : ""} mx-5 mb-5 ${image ? "mt-12" : "mt-0 xl:mt-0"} xl:my-20 md:px-5 xl:px-10`}
      >
        {title && (
          <Text
            as={enableHeading ? "h1" : "h2"}
            className="heading2 md:heading1 text-center"
          >
            {title}
          </Text>
        )}
        {subTitle && (
          <Text
            as={enableHeading ? "h2" : "h3"}
            className="subheading1 mt-4 text-center"
          >
            {subTitle}
          </Text>
        )}

        <div
          className={`mt-8 flex flex-col items-center xl:flex-row ${image ? "xl:mt-16" : "xl:mt-10"} gap-10`}
        >
          <div
            className={`flex flex-col gap-10 self-stretch xl:flex-[1_0_0] ${image ? "xl:items-start pl-2 md:px-4 lg:pl-12 xl:pl-16" : "items-center"}`}
          >
            {description && (
              <Text as="p" className={`body1 text-center${image ? " lg:text-left" : ""}`}>
                {description}
              </Text>
            )}
            {list.length > 0 && (
              <>
                <ul className="grid w-full grid-cols-2 gap-x-6 gap-y-5 md:hidden">
                  {(() => {
                    const sortedList = [...list].sort((a, b) =>
                      a.name.localeCompare(b.name)
                    );
                    const numColumns = 2;
                    const numRows = Math.ceil(sortedList.length / numColumns);
                    const rearranged = [];
                    for (let row = 0; row < numRows; row++) {
                      for (let col = 0; col < numColumns; col++) {
                        const index = col * numRows + row;
                        if (index < sortedList.length) {
                          rearranged.push(sortedList[index]);
                        }
                      }
                    }
                    return rearranged.map((item, index: number) => (
                      <li key={`item-list-2-${index}`}>
                        <Link
                          href={getLocationHref(item.code)}
                          className="label1"
                        >
                          {item.name}
                        </Link>
                      </li>
                    ));
                  })()}
                </ul>
                <ul
                  className={`hidden ${image ? "gap-x-6" : "gap-x-20"} gap-y-5 md:grid md:grid-cols-3 ${image ? "" : "xl:hidden"}`}
                >
                  {(() => {
                    const sortedList = [...list].sort((a, b) =>
                      a.name.localeCompare(b.name)
                    );

                    const numColumns = 3;
                    const numRows = Math.ceil(sortedList.length / numColumns);
                    const rearranged = [];
                    for (let row = 0; row < numRows; row++) {
                      for (let col = 0; col < numColumns; col++) {
                        const index = col * numRows + row;
                        rearranged.push(index < sortedList.length ? sortedList[index] : null); // ← holds position
                      }
                    }
                    return rearranged.map((item, index: number) =>
                      item ? (
                        <li
                          key={`item-list-3-${index}`}
                          className={`${image ? "" : "w-[172px]"}`}
                        >
                          <Link
                            href={getLocationHref(item.code)}
                            className="label1"
                          >
                            {item.name}
                          </Link>
                        </li>
                      ) : (
                        <li key={`empty-3-${index}`} aria-hidden="true" />
                      )
                    );
                  })()}
                </ul>
                {!image && (
                  <ul className="hidden gap-x-20 gap-y-5 xl:grid xl:grid-cols-4">
                    {(() => {
                      const sortedList = [...list].sort((a, b) =>
                        a.name.localeCompare(b.name)
                      );
                      const numColumns = 4;
                      const numRows = Math.ceil(sortedList.length / numColumns);
                      const rearranged = [];
                      for (let row = 0; row < numRows; row++) {
                        for (let col = 0; col < numColumns; col++) {
                          const index = col * numRows + row;
                          rearranged.push(index < sortedList.length ? sortedList[index] : null);
                        }
                      }
                      return rearranged.map((item, index: number) =>
                        item ? (
                          <li
                            key={`item-list-4-${index}`}
                            className="w-[172px]"
                          >
                            <Link
                              href={getLocationHref(item.code)}
                              className="label1"
                            >
                              {item.name}
                            </Link>
                          </li>
                        ) : (
                          <li key={`empty-4-${index}`} aria-hidden="true" />
                        )
                      );
                    })()}
                  </ul>
                )}
              </>
            )}
          </div>
          {image && (
            <aside className="hidden md:block">
              <NextImage width={472} height={100} src={image} alt="image" />
            </aside>
          )}
        </div>
      </div>
    </div>
  );
};

export default FindKinetic;
