/* eslint-disable formatjs/no-literal-string-in-jsx */

"use client"
import { useState } from "react"

import { languages } from "@/constants/languages"
import { env } from "@/env/client"

import useLang from "@/hooks/useLang"

import styles from "./mobile.module.css"

import type { Lang } from "@scandic-hotels/common/constants/language"

import type { LanguageSwitcherProps } from "@/types/components/current/languageSwitcher"

export default function Mobile({ urls }: LanguageSwitcherProps) {
  const currentLanguage = useLang()
  const [isOpen, setIsOpen] = useState(false)

  function toggleOpen() {
    setIsOpen((prevIsOpen) => !prevIsOpen)
  }
  const urlKeys = Object.keys(urls)

  if (urlKeys.length === 1 && urlKeys[0] === currentLanguage) {
    return <div className={styles.toggle}>{languages[currentLanguage]}</div>
  }

  return (
    <section className={styles.mobile}>
      <div>
        <button
          aria-pressed="false"
          className={styles.toggle}
          onClick={toggleOpen}
        >
          {languages[currentLanguage]}{" "}
          <span
            className={`${styles.arrow} ${isOpen ? styles.open : ""}`}
          ></span>
          <span className={styles.hiddenAccessible}>Choose language</span>
        </button>
        <ul className={`${styles.dropdown} ${isOpen ? styles.isOpen : ""}`}>
          {urlKeys.map((key) => {
            const url = urls[key as Lang]?.url
            if (url) {
              return (
                <li key={key} className={styles.li}>
                  <a
                    href={url}
                    className={styles.link}
                    rel={env.isLangLive(key as Lang) ? undefined : "nofollow"}
                  >
                    {languages[key as Lang]}
                  </a>
                </li>
              )
            }
          })}
        </ul>
      </div>
    </section>
  )
}
