"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import type { CommonContent } from "@/content/types";
import { locales, type Locale } from "@/lib/i18n";

type BottomNavProps = {
  locale: Locale;
  common: CommonContent;
};

export default function BottomNav({ locale, common }: BottomNavProps) {
  const pathname = usePathname();
  const segments = pathname.split("/").filter(Boolean);

  const normalizedPath = pathname !== "/" && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
  const homePath = `/${locale}`;
  const aboutPath = `/${locale}/about`;
  const contactPath = `/${locale}/contact`;

  const isHome = normalizedPath === homePath;
  const isAbout = normalizedPath === aboutPath || normalizedPath.startsWith(`${aboutPath}/`);
  const isContact = normalizedPath === contactPath || normalizedPath.startsWith(`${contactPath}/`);
  const targetLocale: Locale = locale === "ar" ? "en" : "ar";

  const switchPath = () => {
    const nextSegments = [...segments];

    if (nextSegments.length === 0) {
      return `/${targetLocale}`;
    }

    if (locales.includes(nextSegments[0] as Locale)) {
      nextSegments[0] = targetLocale;
    } else {
      nextSegments.unshift(targetLocale);
    }

    return `/${nextSegments.join("/")}`;
  };

  return (
    <nav aria-label={common.navLabel} className="bottom-nav">
      <div className="container bottom-nav-inner">
        <div className="bottom-nav-links">
          <Link href={homePath} className={isHome ? "active" : undefined} aria-current={isHome ? "page" : undefined}>
            <span aria-hidden className="nav-icon">
              ○
            </span>
            {common.nav.home}
          </Link>
          <Link href={aboutPath} className={isAbout ? "active" : undefined} aria-current={isAbout ? "page" : undefined}>
            <span aria-hidden className="nav-icon">
              □
            </span>
            {common.nav.about}
          </Link>
          <Link
            href={contactPath}
            className={isContact ? "active" : undefined}
            aria-current={isContact ? "page" : undefined}
          >
            <span aria-hidden className="nav-icon">
              ◇
            </span>
            {common.nav.contact}
          </Link>
          <Link href={switchPath()} className="lang-toggle" aria-label={common.languageSwitcherLabel}>
            <span aria-hidden className="nav-icon">
              ⇄
            </span>
            {targetLocale.toUpperCase()}
          </Link>
        </div>
      </div>
    </nav>
  );
}
