"use client";

import { ReactNode } from "react";
import { OrderedListProps } from "./types";

import { Link } from "@shared/components/link";
import { Text } from "@shared/components/text";
import { DynamicTabs } from "@shared/contentful/blocks/dynamic-tabs";

export const OrderedList = ({
  anchorId,
  backgroundColor = "white",
  title,
  description,
  tabs,
}: OrderedListProps) => {
  const formatItemName = (name: string) =>
    name
      .split(" ")
      .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
      .join(" ");

  // Child rendering for a single list item (itemName / itemSlug). The tab
  // section UI and the column wrapper for these nodes live in DynamicTabs.
  const renderChild = (
    item: OrderedListProps["tabs"][number]["items"]["tabContent"][number],
    index: number
  ): ReactNode => {
    if (!item.itemSlug) {
      return (
        <Text
          key={`ordered-item-${index}`}
          className="body1 relative text-left font-semibold leading-7"
        >
          {formatItemName(item.itemName)}
        </Text>
      );
    }

    return (
      <Link
        key={`ordered-item-${index}`}
        href={item.itemSlug}
        title={item.itemName.toUpperCase()}
        className="flex items-center underline underline-offset-4"
      >
        <Text className="body1 relative cursor-pointer text-left font-semibold leading-7">
          {formatItemName(item.itemName)}
        </Text>
      </Link>
    );
  };

  // Build the DynamicTabs `tabs` prop. Each tab's `tabContent` holds the list
  // of React nodes; DynamicTabs arranges them into columns in ordered mode.
  const dynamicTabs = {
    items: tabs.map((tab, index) => ({
      tabName: tab.items.tabName,
      anchorId: `tab-${index}`,
      tabContent: tab.items.tabContent.map(renderChild),
    })),
  };

  return (
    <section
      className={`bg-secondary-${backgroundColor}`}
      data-testid="non-fiber-city-list"
      id={anchorId}
    >
      <div className="mx-auto w-full max-w-120 px-0 py-12 md:px-6 md:py-20 lg:px-3">
        <div className="mb-11 px-4 md:px-0">
          <Text as={"h2"} className="heading2 text-center md:heading1">
            {title}
          </Text>
          <Text
            as={"h3"}
            className="subheading3 mt-2 text-center md:subheading1"
          >
            {description}
          </Text>
        </div>
        <div className="section-body">
          {dynamicTabs.items.length > 0 ? (
            <div>
              <DynamicTabs
                dynamic={true}
                isOrderedList={true}
                tabs={dynamicTabs}
                navigationType={false}
                mobileSidebarTabType={false}
              />
            </div>
          ) : null}
        </div>
      </div>
    </section>
  );
};

export default OrderedList;
