import { toggleMobileSidebar } from "./sidebar";
import { t } from "./i18n";

const KEYBOARD_THRESHOLD_PX = 100;
const BADGE_REFRESH_MS = 60_000;

export function initBottomNav(): void {
  const nav = document.getElementById("bottom-nav");
  if (!nav) return;

  initMenuSlot();
  initQuickAddSheet();
  initKeyboardWatcher();
  initAgendaBadge();
}

function initMenuSlot(): void {
  const btn = document.getElementById("bottom-nav-menu");
  btn?.addEventListener("click", (e) => {
    e.preventDefault();
    toggleMobileSidebar();
  });
}

function initQuickAddSheet(): void {
  const trigger = document.getElementById("bottom-nav-add") as HTMLButtonElement | null;
  const dialog = document.getElementById("quick-add-sheet") as HTMLDialogElement | null;
  const cancel = document.getElementById("quick-add-cancel") as HTMLButtonElement | null;
  if (!trigger || !dialog) return;

  trigger.addEventListener("click", (e) => {
    e.preventDefault();
    if (typeof dialog.showModal === "function") {
      dialog.showModal();
    } else {
      dialog.setAttribute("open", "");
    }
    dialog.classList.add("is-open");
  });

  function close(): void {
    dialog!.classList.remove("is-open");
    if (typeof dialog!.close === "function") {
      dialog!.close();
    } else {
      dialog!.removeAttribute("open");
    }
  }

  cancel?.addEventListener("click", close);

  dialog.addEventListener("click", (e) => {
    if (e.target === dialog) close();
  });

  dialog.addEventListener("close", () => {
    dialog.classList.remove("is-open");
  });

  dialog.querySelectorAll<HTMLAnchorElement>(".quick-add-row").forEach((row) => {
    row.addEventListener("click", () => {
      // Native <a> navigation handles routing; close sheet first so it
      // does not flash on next page paint via bfcache.
      close();
    });
  });
}

function initKeyboardWatcher(): void {
  const vv = window.visualViewport;
  if (!vv) return;

  let baseHeight = window.innerHeight;
  window.addEventListener("orientationchange", () => {
    setTimeout(() => {
      baseHeight = window.innerHeight;
      document.body.classList.remove("keyboard-open");
    }, 250);
  });

  const handler = () => {
    const delta = baseHeight - vv.height;
    document.body.classList.toggle("keyboard-open", delta > KEYBOARD_THRESHOLD_PX);
  };
  vv.addEventListener("resize", handler);
}

function initAgendaBadge(): void {
  const badge = document.getElementById("bottom-nav-agenda-badge");
  if (!badge) return;

  function refresh(): void {
    fetch("/api/deadlines/summary", { credentials: "same-origin" })
      .then((r) => (r.ok ? r.json() : null))
      .then((data: { overdue?: number; today?: number } | null) => {
        if (!data) return;
        const overdue = typeof data.overdue === "number" ? data.overdue : 0;
        const today = typeof data.today === "number" ? data.today : 0;
        const total = overdue + today;
        if (total <= 0) {
          badge!.style.display = "none";
          badge!.classList.remove("bottom-nav-badge-overdue");
          badge!.removeAttribute("title");
          badge!.removeAttribute("aria-label");
          return;
        }
        badge!.textContent = total > 9 ? "9+" : String(total);
        badge!.style.display = "";
        badge!.classList.toggle("bottom-nav-badge-overdue", overdue > 0);
        // F-38: the badge counts "actionable" items only — overdue + due
        // today. The accessible label spells that out so the "2" never
        // reads as ambiguous (e.g. "2 things this week").
        const label = t("bottomnav.badge.deadlines")
          .replace("{overdue}", String(overdue))
          .replace("{today}", String(today));
        badge!.setAttribute("title", label);
        badge!.setAttribute("aria-label", label);
        badge!.setAttribute("aria-hidden", "false");
      })
      .catch(() => {
        // Badge is decorative; never break the page.
      });
  }

  refresh();
  setInterval(refresh, BADGE_REFRESH_MS);
}
