import { useMemo } from "react";

import { extendCommonContentStylesheet } from "@devowl-wp/web-cookie-banner";

import { useBanner } from "../../contexts/banner.js";
import { useStylesheet } from "../../contexts/stylesheet.js";

import type { FC } from "react";

const LanguageSwitcher: FC = () => {
    const { FooterLanguageSwitcherSelect } = useStylesheet().extend(...extendCommonContentStylesheet);
    const {
        footerDesign: { languageSwitcher: languageSwitcherChoice },
        languageSwitcher,
        onLanguageSwitch,
    } = useBanner();
    const current = useMemo(() => languageSwitcher.find(({ current }) => current), [languageSwitcher]);
    const hasFlag = languageSwitcherChoice === "flags" && !!current?.flag;

    return (
        <FooterLanguageSwitcherSelect data-flag={hasFlag}>
            {hasFlag && <span style={{ backgroundImage: `url(${current.flag})` }} />}
            <select
                value={current?.locale}
                aria-label={current?.name}
                onChange={(e) => {
                    onLanguageSwitch?.(
                        languageSwitcher.find(({ locale }) => locale === (e.target as HTMLSelectElement).value),
                    );
                }}
            >
                {languageSwitcher.map(({ locale, name }) => (
                    <option value={locale} key={locale}>
                        {name}
                    </option>
                ))}
            </select>
        </FooterLanguageSwitcherSelect>
    );
};

export { LanguageSwitcher };
