"use client";

import { useSyncExternalStore } from "react";
import { useTheme } from "next-themes";

const OPTIONS = [
  { value: "light", label: "Light" },
  { value: "dark", label: "Dark" },
  { value: "system", label: "System" },
] as const;

const noopSubscribe = () => () => {};

export function ThemeToggle({ className = "" }: { className?: string }) {
  const { theme, setTheme } = useTheme();
  // next-themes can't know the persisted/system theme until after hydration,
  // so render a fixed-size placeholder first to avoid a light/dark flash or
  // mismatch, then swap in the real control once mounted. useSyncExternalStore
  // (server snapshot false, client snapshot true) is the hydration-safe way
  // to get a "have we mounted on the client yet" flag.
  const mounted = useSyncExternalStore(
    noopSubscribe,
    () => true,
    () => false,
  );

  if (!mounted) {
    return (
      <div
        className={`h-8 w-[132px] rounded-full border border-charcoal/20 ${className}`}
        aria-hidden="true"
      />
    );
  }

  return (
    <div
      role="radiogroup"
      aria-label="Theme"
      className={`flex items-center rounded-full border border-charcoal/20 p-0.5 text-xs font-medium ${className}`}
    >
      {OPTIONS.map((option) => (
        <button
          key={option.value}
          type="button"
          role="radio"
          aria-checked={theme === option.value}
          onClick={() => setTheme(option.value)}
          className={`rounded-full px-3 py-1 transition-colors ${
            theme === option.value
              ? "bg-terracotta text-white"
              : "text-charcoal/60 hover:text-charcoal"
          }`}
        >
          {option.label}
        </button>
      ))}
    </div>
  );
}
