"use client";

import { useSyncExternalStore } from "react";

export type SidebarTone = "light" | "brand";

import { SIDEBAR_TONE_KEY as KEY } from "@/lib/sidebar-tone-script";
const listeners = new Set<() => void>();
// In-memory copy so the switch still works for this visit when storage is blocked.
let memory: SidebarTone | null = null;

function read(): SidebarTone {
  if (memory) return memory;
  try {
    return localStorage.getItem(KEY) === "brand" ? "brand" : "light";
  } catch {
    return "light";
  }
}

function subscribe(onChange: () => void) {
  listeners.add(onChange);
  window.addEventListener("storage", onChange);
  return () => {
    listeners.delete(onChange);
    window.removeEventListener("storage", onChange);
  };
}

function setTone(tone: SidebarTone) {
  memory = tone;
  try {
    localStorage.setItem(KEY, tone);
  } catch {
    // Storage blocked: the in-memory copy carries it.
  }
  document.documentElement.dataset.sidebarTone = tone; // the theme CSS follows <html>, as at first paint
  listeners.forEach((l) => l());
}

/** Lets the showcase compare the two sidebar tones live. Remembered per browser; light on the server and by default. */
export function useSidebarTone() {
  const tone = useSyncExternalStore(subscribe, read, () => "light" as const);
  return { tone, setTone };
}
