"use client";

import { useEffect, useRef, useState, type MouseEvent } from "react";

import {
  LOCALE_OPTIONS,
  type SupportedLocale,
} from "@/lib/i18n-config";
import { getLocalizedPublicPath } from "@/lib/i18n-urls";

const noticeCopy: Record<
  Exclude<SupportedLocale, "ko">,
  { action: string; dismiss: string; message: string }
> = {
  en: {
    action: "View in English",
    dismiss: "Stay in Korean",
    message: "OfficialMail is available in English.",
  },
  zh: {
    action: "查看简体中文",
    dismiss: "继续使用韩语",
    message: "OfficialMail 提供简体中文版本。",
  },
  ja: {
    action: "日本語で見る",
    dismiss: "韓国語のまま見る",
    message: "OfficialMailは日本語でご利用いただけます。",
  },
  vi: {
    action: "Xem bằng tiếng Việt",
    dismiss: "Tiếp tục bằng tiếng Hàn",
    message: "OfficialMail có phiên bản tiếng Việt.",
  },
  ru: {
    action: "Открыть на русском",
    dismiss: "Остаться на корейском",
    message: "OfficialMail доступен на русском языке.",
  },
};

function GlobeIcon({ className = "h-[18px] w-[18px]" }: { className?: string }) {
  return (
    <svg
      aria-hidden="true"
      className={className}
      fill="none"
      stroke="currentColor"
      strokeLinecap="round"
      strokeLinejoin="round"
      strokeWidth="1.7"
      viewBox="0 0 24 24"
    >
      <circle cx="12" cy="12" r="9" />
      <path d="M3.5 12h17" />
      <path d="M12 3c2.4 2.5 3.7 5.5 3.7 9s-1.3 6.5-3.7 9c-2.4-2.5-3.7-5.5-3.7-9S9.6 5.5 12 3Z" />
    </svg>
  );
}

function navigateToLocalizedDocument(
  event: MouseEvent<HTMLAnchorElement>,
  href: string,
) {
  if (
    event.defaultPrevented ||
    event.button !== 0 ||
    event.metaKey ||
    event.ctrlKey ||
    event.shiftKey ||
    event.altKey
  ) {
    return;
  }

  event.preventDefault();

  const target = new URL(href, window.location.origin);
  target.search = window.location.search;
  target.hash = window.location.hash;

  // Locale prefixes are resolved by Proxy request headers, so this must be a
  // full document navigation rather than a cached App Router transition.
  window.location.assign(target.toString());
}

export function PublicLanguageMenu({
  currentLocale,
  pathname = "/",
}: {
  currentLocale: SupportedLocale;
  pathname?: string;
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;

    const closeOnOutsideClick = (event: PointerEvent) => {
      if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
    };
    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };

    document.addEventListener("pointerdown", closeOnOutsideClick);
    document.addEventListener("keydown", closeOnEscape);
    return () => {
      document.removeEventListener("pointerdown", closeOnOutsideClick);
      document.removeEventListener("keydown", closeOnEscape);
    };
  }, [open]);

  return (
    <div ref={rootRef} className="relative">
      <button
        type="button"
        aria-expanded={open}
        aria-haspopup="menu"
        aria-label="언어 선택"
        className="inline-flex h-10 min-w-10 cursor-pointer items-center justify-center gap-1.5 rounded-[12px] border border-[#dbe5f7] bg-white/80 px-2.5 text-[#526784] shadow-[0_8px_22px_rgba(47,109,246,0.06)] transition-all hover:-translate-y-0.5 hover:border-[#b9cdf8] hover:bg-[#f4f8ff] hover:text-[#2f6df6] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2f6df6]/35 sm:h-11"
        onClick={() => setOpen((value) => !value)}
      >
        <GlobeIcon />
        <span className="hidden text-[11px] font-bold uppercase sm:inline">
          {currentLocale}
        </span>
      </button>

      {open ? (
        <div
          role="menu"
          className="absolute right-0 top-[calc(100%+10px)] z-[80] w-[210px] overflow-hidden rounded-[16px] border border-[#dce6f5] bg-white p-2 shadow-[0_22px_60px_rgba(25,48,91,0.18)]"
        >
          <p className="px-3 pb-2 pt-1.5 text-[10px] font-bold uppercase tracking-[0.14em] text-[#91a0b6]">
            Language
          </p>
          {LOCALE_OPTIONS.map((option) => {
            const active = option.code === currentLocale;
            const href = getLocalizedPublicPath(pathname, option.code);
            return (
              <a
                key={option.code}
                role="menuitem"
                href={href}
                aria-current={active ? "page" : undefined}
                className={`flex items-center justify-between rounded-[10px] px-3 py-2.5 text-[13px] font-semibold transition-colors ${
                  active
                    ? "bg-[#edf4ff] text-[#2f6df6]"
                    : "text-[#42536e] hover:bg-[#f5f8fd] hover:text-[#2f6df6]"
                }`}
                onClick={(event) => {
                  setOpen(false);
                  navigateToLocalizedDocument(event, href);
                }}
              >
                <span>{option.nativeLabel}</span>
                <span className="text-[10px] font-bold uppercase text-[#9aa8bc]">
                  {option.code}
                </span>
              </a>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}

export function PublicLocaleSuggestion({
  countryLocale,
  pathname = "/",
}: {
  countryLocale: SupportedLocale | null;
  pathname?: string;
}) {
  const [dismissed, setDismissed] = useState(false);
  const suggestedLocale = countryLocale === "ko" ? null : countryLocale;

  if (!suggestedLocale || dismissed) return null;

  const copy = noticeCopy[suggestedLocale];

  const dismiss = () => {
    setDismissed(true);
  };

  return (
    <aside className="relative z-30 h-14 border-b border-[#dce7f8] bg-[#f5f9ff] text-[#29405f] sm:h-12">
      <div className="mx-auto flex h-full w-full max-w-[1420px] items-center justify-between gap-2 px-4 sm:gap-4 sm:px-8 xl:px-10">
        <div className="flex min-w-0 items-center gap-2.5">
          <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-white text-[#2f6df6] shadow-[0_5px_16px_rgba(47,109,246,0.12)]">
            <GlobeIcon className="h-4 w-4" />
          </span>
          <p className="truncate text-[11px] font-semibold leading-5 sm:text-[13px]">
            {copy.message}
          </p>
        </div>
        <div className="flex shrink-0 items-center gap-2">
          <a
            href={getLocalizedPublicPath(pathname, suggestedLocale)}
            className="inline-flex h-8 items-center rounded-[9px] bg-[#2f6df6] px-3 text-[11px] font-bold text-white transition-colors hover:bg-[#245de3] sm:text-[12px]"
            onClick={(event) =>
              navigateToLocalizedDocument(
                event,
                getLocalizedPublicPath(pathname, suggestedLocale),
              )
            }
          >
            {copy.action}
          </a>
          <button
            type="button"
            className="hidden h-8 cursor-pointer px-2 text-[11px] font-semibold text-[#71829b] transition-colors hover:text-[#344b6b] sm:inline-flex sm:items-center sm:text-[12px]"
            onClick={dismiss}
          >
            {copy.dismiss}
          </button>
        </div>
      </div>
    </aside>
  );
}
