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

import { Lang, languages } from "@/constants/languages"

import useLang from "@/hooks/useLang"

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

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}>
                    {languages[key as Lang]}
                  </a>
                </li>
              )
            }
          })}
        </ul>
      </div>
    </section>
  )
}
