import { Alpine } from "./alpine";
import { ALL_LIBRARIES, getSelectedLibrary, setSelectedLibrary } from "./storage";
import { showToast } from "./toast";

export function getCurrentLibraryId(): string {
  return getSelectedLibrary();
}

export async function switchWithTransition(
  containerId: string,
  fetchFn: () => Promise<void>,
): Promise<void> {
  const container = document.getElementById(containerId);
  const loading = document.getElementById("loading-spinner");

  if (!container || !loading) return;

  try {
    container.classList.add(
      "opacity-0",
      "transition-opacity",
      "duration-150",
    );
    await new Promise((resolve) => setTimeout(resolve, 150));

    loading.classList.remove("hidden");

    await fetchFn();

    container.classList.remove("duration-150");
    container.classList.add("duration-300");
    void container.offsetHeight;
    container.classList.remove("opacity-0");

    setTimeout(() => {
      container.classList.remove("transition-opacity", "duration-300");
    }, 300);
  } catch (error) {
    container.classList.remove(
      "opacity-0",
      "transition-opacity",
      "duration-150",
      "duration-300",
    );
    showToast("Failed to load library", "error");
    console.error("Switch library error:", error);
  } finally {
    loading.classList.add("hidden");
  }
}

export interface LibrarySwitcherOptions {
  onSwitch: (libraryId: string) => Promise<void>;
}

export function initLibrarySwitcher(options: LibrarySwitcherOptions): void {
  const librarySelect = document.getElementById(
    "library-select",
  ) as HTMLSelectElement;
  if (!librarySelect) return;

  const stored = localStorage.getItem("selectedLibrary");
  if (stored === ALL_LIBRARIES) {
    librarySelect.value = "";
  } else if (stored) {
    const option = librarySelect.querySelector(
      `option[value="${stored}"]`,
    );
    if (option) {
      librarySelect.value = stored;
    }
  }

  librarySelect.addEventListener("change", async (e) => {
    const target = e.target as HTMLSelectElement;
    const libraryId = target.value;

    setSelectedLibrary(libraryId);
    await options.onSwitch(libraryId);
  });
}

Alpine.data("librarySwitcher", () => ({}));
