import { useState } from "react";
import styles from "./ThemeToggle.module.css";

const THEMES = [
  { id: "dark-parchment", label: "Dark Parchment", icon: "\u{1F4DC}" },
  { id: "light-parchment", label: "Light Parchment", icon: "\u{1F3F0}" },
  { id: "white", label: "White", icon: "\u2600" },
  { id: "abyss", label: "Abyss", icon: "\u{1F311}" },
] as const;

type ThemeId = (typeof THEMES)[number]["id"];

function getInitialTheme(): ThemeId {
  const saved = localStorage.getItem("shadowdark-theme");
  if (saved && THEMES.some((t) => t.id === saved)) return saved as ThemeId;
  return "dark-parchment";
}

function applyTheme(theme: ThemeId) {
  if (theme === "dark-parchment") {
    document.documentElement.removeAttribute("data-theme");
  } else {
    document.documentElement.setAttribute("data-theme", theme);
  }
  localStorage.setItem("shadowdark-theme", theme);
}

// Apply saved theme immediately on module load
applyTheme(getInitialTheme());

export default function ThemeToggle() {
  const [current, setCurrent] = useState<ThemeId>(getInitialTheme);
  const [open, setOpen] = useState(false);

  function selectTheme(theme: ThemeId) {
    applyTheme(theme);
    setCurrent(theme);
    setOpen(false);
  }

  const currentTheme = THEMES.find((t) => t.id === current)!;

  return (
    <div className={styles.container}>
      <button
        className={styles.trigger}
        onClick={() => setOpen(!open)}
        title="Change theme"
      >
        {currentTheme.icon}
      </button>
      {open && (
        <div className={styles.dropdown}>
          {THEMES.map((theme) => (
            <button
              key={theme.id}
              className={`${styles.option} ${theme.id === current ? styles.active : ""}`}
              onClick={() => selectTheme(theme.id)}
            >
              <span className={styles.optionIcon}>{theme.icon}</span>
              <span>{theme.label}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
