"use client";

import React from "react";
import { usePathname, useRouter } from "next/navigation";
import { useI18n } from "@/lib/i18n/context";
import { localizePathname } from "@/lib/seo/slugs";

export function LanguageSwitch() {
  const { lang, setLang } = useI18n();
  const pathname = usePathname();
  const router = useRouter();

  const switchTo = (target: "de" | "en") => {
    if (/^\/(de|en)(?=\/|$)/.test(pathname)) {
      // Marketing routes live at /de and /en. SEO pages have locale-specific
      // slugs, so swapping the prefix alone is not enough.
      router.push(localizePathname(pathname, target));
    } else {
      setLang(target);
    }
  };

  return (
    <div className="inline-flex items-center bg-[#F6F9FF] p-1 border border-[#E2E8F0]">
      <button
        onClick={() => switchTo("de")}
        className={`flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono font-semibold transition-all ${
          lang === "de"
            ? "bg-white text-black border border-[#E2E8F0]"
            : "text-[#64748B] hover:text-black border border-transparent"
        }`}
        title="Deutsch (DACH)"
      >
        <span className="text-sm">🇩🇪</span>
        <span>DE</span>
      </button>
      <button
        onClick={() => switchTo("en")}
        className={`flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono font-semibold transition-all ${
          lang === "en"
            ? "bg-white text-black border border-[#E2E8F0]"
            : "text-[#64748B] hover:text-black border border-transparent"
        }`}
        title="English (US/Global)"
      >
        <span className="text-sm">🇺🇸</span>
        <span>EN</span>
      </button>
    </div>
  );
}