Spaces:
Sleeping

File size: 1,776 Bytes
cc54add
 
 
 
 
c28cca2
cc54add
 
 
 
 
 
 
 
 
 
c28cca2
 
cc54add
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"use client";

import { useEffect, useState } from "react";

export default function ThemeToggle() {
  const [theme, setTheme] = useState("dark");
  const isDark = theme === "dark";

  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const stored = window.localStorage.getItem("theme");
      if (stored === "dark" || stored === "light") {
        setTheme(stored);
        document.documentElement.classList.toggle("dark", stored === "dark");
      } else {
        // Default to dark theme for a forensic look if no preference stored
        const initial = "dark";
        setTheme(initial);
        document.documentElement.classList.toggle("dark", initial === "dark");
      }
    } catch (e) {
      // ignore
    }
  }, []);

  const toggle = () => {
    const next = isDark ? "light" : "dark";
    setTheme(next);
    if (typeof window !== "undefined") {
      try {
        window.localStorage.setItem("theme", next);
      } catch (e) {}
    }
    if (typeof document !== "undefined") {
      document.documentElement.classList.toggle("dark", next === "dark");
    }
  };

  return (
    <button
      type="button"
      onClick={toggle}
      className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full border border-gray-200 bg-white text-xs font-medium shadow-sm hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700"
      aria-label="Toggle dark mode"
    >
      <span className="h-4 w-4 flex items-center justify-center rounded-full bg-gray-900 text-[10px] text-yellow-300 dark:bg-yellow-400 dark:text-gray-900">
        {isDark ? "☾" : "☀"}
      </span>
      <span className="hidden sm:inline text-gray-700 dark:text-gray-200">{isDark ? "Dark" : "Light"} mode</span>
    </button>
  );
}