"use client";
import { useState } from "react";

export default function AdminThemeToggle({ initialTheme }: { initialTheme: string }) {
  const [theme, setTheme] = useState(initialTheme);

  function toggle() {
    const next = theme === "day" ? "night" : "day";
    setTheme(next);
    // Instant visual feedback — flip the attribute on the admin root
    // element directly, rather than waiting on a round trip + refresh.
    document.querySelector("[data-admin-theme]")?.setAttribute("data-admin-theme", next);
    fetch("/api/admin/theme", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ theme: next }),
    }).catch(() => {});
  }

  return (
    <button
      onClick={toggle}
      className="w-9 h-9 rounded-lg flex items-center justify-center text-neutral-400 hover:text-white hover:bg-neutral-800 transition-colors"
      title={theme === "day" ? "Switch to night mode" : "Switch to day mode"}
      aria-label="Toggle theme"
    >
      {theme === "day" ? "🌙" : "☀️"}
    </button>
  );
}
