"use client";

import { useEffect, useState } from "react";
import { Moon, Sun } from "lucide-react";

type Theme = "light" | "gray" | "black";

const THEME_STORAGE_KEY = "forgeworks-theme";
const THEME_COOKIE_KEY = "forgeworks-theme";
const DEFAULT_THEME: Theme = "gray";

function isTheme(value: string | null | undefined): value is Theme {
  return value === "light" || value === "gray" || value === "black";
}

function isForgeworksDomain(hostname: string) {
  return hostname === "myforgeworks.net" || hostname.endsWith(".myforgeworks.net");
}

function readCookieTheme(): Theme | null {
  if (!isForgeworksDomain(window.location.hostname.toLowerCase())) return null;
  const prefix = `${THEME_COOKIE_KEY}=`;
  const item = document.cookie.split("; ").find((part) => part.startsWith(prefix));
  if (!item) return null;

  const value = decodeURIComponent(item.slice(prefix.length));
  return isTheme(value) ? value : null;
}

function readTheme(): Theme {
  const cookieTheme = readCookieTheme();
  if (cookieTheme) return cookieTheme;

  try {
    const storedTheme = localStorage.getItem(THEME_STORAGE_KEY);
    if (isTheme(storedTheme)) return storedTheme;
  } catch {}

  return DEFAULT_THEME;
}

function applyTheme(theme: Theme) {
  document.documentElement.dataset.theme = theme;
  document.documentElement.style.colorScheme = theme === "light" ? "light" : "dark";
  try {
    localStorage.setItem(THEME_STORAGE_KEY, theme);
  } catch {}

  if (isForgeworksDomain(window.location.hostname.toLowerCase())) {
    document.cookie = `${THEME_COOKIE_KEY}=${encodeURIComponent(theme)}; Max-Age=31536000; Path=/; Domain=myforgeworks.net; SameSite=Lax; Secure`;
  }
}

export function ThemeSwitch() {
  const [theme, setTheme] = useState<Theme>(DEFAULT_THEME);

  useEffect(() => {
    const syncTheme = () => {
      const preferredTheme = readTheme();
      setTheme((currentTheme) => {
        if (currentTheme !== preferredTheme) applyTheme(preferredTheme);
        return preferredTheme;
      });
    };
    const syncVisibleTheme = () => {
      if (document.visibilityState === "visible") syncTheme();
    };

    syncTheme();
    window.addEventListener("focus", syncTheme);
    window.addEventListener("pageshow", syncTheme);
    window.addEventListener("storage", syncTheme);
    document.addEventListener("visibilitychange", syncVisibleTheme);

    return () => {
      window.removeEventListener("focus", syncTheme);
      window.removeEventListener("pageshow", syncTheme);
      window.removeEventListener("storage", syncTheme);
      document.removeEventListener("visibilitychange", syncVisibleTheme);
    };
  }, []);

  return (
    <div
      className="theme-switch"
      role="group"
      aria-label="Colour theme"
      suppressHydrationWarning
    >
      <button
        type="button"
        aria-label="Light mode"
        aria-pressed={theme === "light"}
        className={theme === "light" ? "active" : ""}
        onClick={() => { setTheme("light"); applyTheme("light"); }}
      >
        <Sun size={14} aria-hidden="true" />
      </button>
      <button
        type="button"
        aria-label="Dark gray mode"
        aria-pressed={theme === "gray"}
        className={theme === "gray" ? "active" : ""}
        onClick={() => { setTheme("gray"); applyTheme("gray"); }}
      >
        <Moon size={14} aria-hidden="true" />
      </button>
      <button
        type="button"
        aria-label="Pure black mode"
        aria-pressed={theme === "black"}
        className={`black-dot ${theme === "black" ? "active" : ""}`}
        onClick={() => { setTheme("black"); applyTheme("black"); }}
      >
        <span aria-hidden="true" />
      </button>
    </div>
  );
}
