import { Alpine } from "./alpine";
import { applyTheme } from "./theme";
import { getToken } from "./storage";

function initIndexTheme(): void {
  // Progressive enhancement: check localStorage immediately
  const savedTheme = localStorage.getItem("theme");
  if (savedTheme && savedTheme !== "tokyo-night") {
    applyTheme(savedTheme);
  }
}

function changeTheme(): void {
  const select = document.getElementById("theme-select") as HTMLSelectElement;
  if (!select) return;

  const newTheme = select.value;
  applyTheme(newTheme);

  // Save to localStorage
  localStorage.setItem("theme", newTheme);
}

async function checkAuthRedirect(): Promise<void> {
  const token = getToken();
  if (!token) return;

  try {
    const response = await fetch("/api/auth/profile", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    if (response.ok) {
      // Token is valid, redirect to dashboard
      window.location.href = "/dashboard";
    }
  } catch (error) {
    console.error("Failed to check auth", error);
  }
}

export { changeTheme, checkAuthRedirect, initIndexTheme };

Alpine.data("index", () => ({
  changeTheme,
  checkAuthRedirect,
  initIndexTheme,
}));
