---
import Button from "./ui/Button.astro";
import { Icon } from "astro-icon/components";

import { getCollection } from "astro:content";
import { createTranslator, routeTranslations } from "../i18n/index.ts";

const allNews = await getCollection("news");
const allEditorial = await getCollection("editorial");

const tl = createTranslator(Astro.currentLocale);
const currentLocale = Astro.currentLocale;
const currentPath = Astro.url.pathname;
const { locale } = Astro.params;

const languages = [
    { code: "es", icon: "icon_flag_es", label: "Español" },
    { code: "en", icon: "icon_flag_uk", label: "English" },
    { code: "he", icon: "flagpack--il", label: "עברית" },
    { code: "pt", icon: "flagpack--br", label: "Português" },
    { code: "fr", icon: "flagpack--fr", label: "Français" },
    { code: "ru", icon: "flagpack--ru", label: "Русский" },
    { code: "rw", icon: "flagpack--rw", label: "Kinyarwanda" },
    { code: "kr", icon: null, label: "Kreole" },
];

const navItems = [
    { href: "#somos", key: "nav.about" },
    { href: "#programs", key: "nav.programs" },
    { href: "#news", key: "nav.news" },
    { href: "#editorial", key: "nav.editorial" },
];

const sidebarNavItems = [
    { href: `/`, key: "nav.home" },
    { href: "#somos", key: "nav.about" },
    { href: "#programs", key: "nav.programs" },
    { href: "#news", key: "nav.news" },
    { href: "#editorial", key: "nav.editorial" },
];

function translatePath(newLocale: string) {
    const segments = currentPath.split("/").filter(Boolean);
    if (segments.length === 0) return `/${newLocale}`;
    const remainingSegments = segments.slice(1);
    const allRouteNames = Object.values(routeTranslations).flatMap(r => Object.values(r));
    const translatedSegments = remainingSegments.map((segment) => {
        for (const key in routeTranslations) {
            const translations =
                routeTranslations[key as keyof typeof routeTranslations];
            if (Object.values(translations).includes(segment)) {
                return (
                    translations[newLocale as keyof typeof translations] ||
                    segment
                );
            }
        }
        return segment;
    });
    if (segments.length >= 2 && allRouteNames.includes(segments[1])) {
        if (segments.length >= 3) {
            const currentId = segments[segments.length - 1];
            const baseId = currentId.split("/").pop();
            const existsInNews = allNews.some(
                (post) =>
                    post.id.endsWith(baseId!) && post.data.locale === newLocale,
            );
            const existsInEditorial = allEditorial.some(
                (post) =>
                    post.id.endsWith(baseId!) && post.data.locale === newLocale,
            );
            if (!existsInNews && !existsInEditorial) return `/${newLocale}/${translatedSegments[0]}`;
            return `/${newLocale}/${translatedSegments[0]}/${newLocale}/${baseId}`;
        }
    }
    return `/${[newLocale, ...translatedSegments].join("/")}`;
}
---

<div>
    <div class="flex justify-between px-8 md:px-0 md:py-4">
        <div class="border-l-4 border-colorPrimary pl-4">
            <p
                class="font-secondary text-colorPrimary font-bold leading-none py-2 text-2xl md:text-lg"
            >
                <a href={`/${currentLocale}`}
                    >{tl("nav.logo_line1")}<br />{tl("nav.logo_line2")}</a
                >
            </p>
        </div>
        <nav
            class="flex justify-end md:justify-evenly gap-4 md:gap-6 lg:gap-10 items-center uppercase text-md text-white"
        >
            <div class="hidden md:flex gap-4 lg:gap-8 font-primary font-bold">
                {
                    navItems.map((item) => (
                        <a
                            class="hover:text-colorPrimary transition"
                            href={`/${currentLocale}${item.href}`}
                        >
                            {tl(item.key)}
                        </a>
                    ))
                }
                <!-- <a class="hover:text-colorPrimary transition" href={`/${currentLocale}/archive`}>{tl("nav.archive")}</a>
        <a class="hover:text-colorPrimary transition" href={`/${currentLocale}/nations`}>{tl("nav.nations")}</a> -->
            </div>
            <div class="drawer md:hidden">
                <input id="my-drawer-1" type="checkbox" class="drawer-toggle" />
                <div class="drawer-content">
                    <label for="my-drawer-1" class="btn-ghost drawer-button">
                        <Icon
                            name="ph:list"
                            class="text-white text-4xl font-bold"
                        />
                    </label>
                </div>
                <div class="drawer-side">
                    <label
                        for="my-drawer-1"
                        aria-label="close sidebar"
                        class="drawer-overlay"></label>
                    <ul
                        class="menu min-h-full w-80 p-4 bg-[url(/img/opacity-logo.png)] bg-no-repeat bg-contain bg-center bg-[#22523F] text-white"
                    >
                        <div
                            class="flex gap-2 justify-center items-center mb-8 mt-8"
                        >
                            <img
                                class="w-1/3 object-contain"
                                src="/img/logo-metalico.webp"
                                alt="Logo Centro del Reino de Paz y Justicia"
                            />
                            <p
                                class="font-secondary text-colorPrimary font-bold leading-none py-2 text-lg"
                            >
                                <a href="/"
                                    >{tl("nav.logo_line1")}<br />{
                                        tl("nav.logo_line2")
                                    }</a
                                >
                            </p>
                        </div>
                        <ul
                            class="font-primary font-bold flex flex-col gap-1 text-lg p-0"
                        >
                            {
                                sidebarNavItems.map((item) => (
                                    <li>
                                        <a
                                            class="hover:text-colorPrimary transition"
                                            href={`/${currentLocale}${item.href}`}
                                        >
                                            {tl(item.key)}
                                        </a>
                                    </li>
                                ))
                            }
                        </ul>
                        <div class="w-50">
                            <Button
                                class="px-8 py-2 uppercase text-lg mt-8"
                                title={tl("nav.contact")}
                                url="#contact"
                                variant="primary"
                            />
                        </div>
                        <div class="dropdown mt-10">
                            <div
                                tabindex="0"
                                role="button"
                                class="btn-ghost m-1 cursor-pointer"
                            >
                                <Icon name="ph:translate" class="text-2xl" />
                            </div>
                            <ul
                                tabindex="-1"
                                class="dropdown-content text-tertiary text-lg bg-colorPrimary menu z-1 w-52 p-2 shadow-sm"
                            >
                                {
                                    languages.map((lang) => (
                                        <li>
                                            <a href={translatePath(lang.code)}>
                                                {lang.icon && (
                                                    <Icon name={lang.icon} />
                                                )}{" "}
                                                {lang.label}
                                            </a>
                                        </li>
                                    ))
                                }
                            </ul>
                        </div>
                    </ul>
                </div>
            </div>
            <div class="w-50 hidden md:block">
                <Button
                    class="px-4 py-2 uppercase"
                    title={tl("nav.contact")}
                    url="#contact"
                    variant="primary"
                />
            </div>
            <div class="dropdown dropdown-end md:block hidden">
                <div
                    tabindex="0"
                    role="button"
                    class="btn-ghost m-1 cursor-pointer"
                >
                    <Icon name="ph:translate" class="text-2xl" />
                </div>
                <ul
                    tabindex="-1"
                    class="dropdown-content text-tertiary text-lg bg-colorPrimary menu z-1 w-52 p-2 shadow-sm"
                >
                    {
                        languages.map((lang) => (
                            <li>
                                <a href={translatePath(lang.code)}>
                                    {lang.icon && <Icon name={lang.icon} />}{" "}
                                    {lang.label}
                                </a>
                            </li>
                        ))
                    }
                </ul>
            </div>
        </nav>
    </div>
</div>
