import { create } from "zustand";

const STORAGE_KEY = "llink:autoplay-muted";

function loadMuted(): boolean {
  try {
    return localStorage.getItem(STORAGE_KEY) === "true";
  } catch {
    return false;
  }
}

function saveMuted(muted: boolean) {
  try {
    localStorage.setItem(STORAGE_KEY, String(muted));
  } catch {
    // Storage unavailable
  }
}

interface AutoplayState {
  /** When true, incoming play requests are ignored */
  muted: boolean;
  /** Toggle muted state */
  toggleMuted: () => void;
}

export const useAutoplayStore = create<AutoplayState>((set, get) => ({
  muted: loadMuted(),
  toggleMuted: () => {
    const next = !get().muted;
    set({ muted: next });
    saveMuted(next);
  },
}));
