'use client';

import images from '@/assets/images/images';
import { TLocales } from '@/models/layout';
import Image from 'next/image';
import { usePathname } from 'next/navigation';

export default function LanguageSwitch() {
  const pathname = usePathname();

  const languages = [
    {
      title: 'EN',
      image: images.langEn,
      locale: 'en',
    },
    {
      title: 'FA',
      image: images.langFa,
      locale: 'fa',
    },
  ];

  const changeLocale = (locale: TLocales) => {
    const currentLocale = pathname.split('/')[1];
    if (currentLocale === locale) return;
    let newPath = pathname.replace(/^\/(en|fa)/, '');
    if (newPath === '/') newPath = '';

    window.location.pathname = `/${locale}${newPath}`;
  };

  return (
    <div className="flex items-center justify-center gap-3">
      {languages.map((language) => (
        <div
          className="flex cursor-pointer flex-col items-center justify-center gap-2 px-1"
          onClick={() => changeLocale(language.locale as TLocales)}
          key={language.title}
        >
          <Image src={language.image} alt={language.title} />
          <span className="text-xs font-normal text-white">
            {language.title}
          </span>
        </div>
      ))}
    </div>
  );
}
