"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useDanmuSettings = exports.useSetDanmuMaxMessages = exports.useSetDanmuLaneCount = exports.useSetDanmuSpeed = exports.useSetDanmuOpacity = exports.useSetDanmuEnabled = exports.useSetDanmuUnlocked = exports.useDanmuMaxMessages = exports.useDanmuLaneCount = exports.useDanmuSpeed = exports.useDanmuOpacity = exports.useDanmuEnabled = exports.useDanmuUnlocked = exports.useEffectiveVolume = exports.useSetMuted = exports.useSetVolume = exports.useMuted = exports.useVolume = exports.useSetContentMetadata = exports.useContentMetadata = exports.useSetHandle = exports.useHandle = exports.useDID = exports.useUrl = exports.makeStreamplaceStore = void 0;
exports.getStreamplaceStoreFromContext = getStreamplaceStoreFromContext;
exports.useStreamplaceStore = useStreamplaceStore;
const tslib_1 = require("tslib");
const react_1 = require("react");
const zustand_1 = require("zustand");
const storage_1 = tslib_1.__importDefault(require("../storage"));
const context_1 = require("../streamplace-provider/context");
const makeStreamplaceStore = ({ url, }) => {
    const VOLUME_STORAGE_KEY = "globalVolume";
    const MUTED_STORAGE_KEY = "globalMuted";
    const DANMU_UNLOCKED_KEY = "danmuUnlocked";
    const DANMU_ENABLED_KEY = "danmuEnabled";
    const DANMU_OPACITY_KEY = "danmuOpacity";
    const DANMU_SPEED_KEY = "danmuSpeed";
    const DANMU_LANE_COUNT_KEY = "danmuLaneCount";
    const DANMU_MAX_MESSAGES_KEY = "danmuMaxMessages";
    const store = (0, zustand_1.createStore)()((set) => ({
        url,
        liveUsers: null,
        setLiveUsers: (opts) => {
            set({
                ...opts,
            });
        },
        liveUsersRefresh: 0,
        liveUsersLoading: true,
        liveUsersError: null,
        oauthSession: null,
        handle: null,
        chatProfile: null,
        ingests: null,
        setIngests: (ingests) => set({ ingests: ingests }),
        broadcasterDID: null,
        setBroadcasterDID: (broadcasterDID) => set({ broadcasterDID }),
        serverDID: null,
        setServerDID: (serverDID) => set({ serverDID }),
        adminDIDs: [],
        setAdminDIDs: (adminDIDs) => set({ adminDIDs }),
        playbackWorkerUrl: null,
        setPlaybackWorkerUrl: (playbackWorkerUrl) => set({ playbackWorkerUrl }),
        gamesEnabled: false,
        setGamesEnabled: (gamesEnabled) => set({ gamesEnabled }),
        // Content metadata
        contentMetadata: null,
        setContentMetadata: (metadata) => set({ contentMetadata: metadata }),
        // Branding state
        branding: null,
        brandingLoading: false,
        brandingError: null,
        // Volume state - start with defaults
        volume: 1.0,
        muted: false,
        setVolume: (volume) => {
            // Ensure the value is finite and within bounds
            if (!Number.isFinite(volume)) {
                console.warn("Invalid volume value:", volume, "- using 1.0");
                volume = 1.0;
            }
            const clampedVolume = Math.max(0, Math.min(1, volume));
            set({ volume: clampedVolume });
            // Auto-unmute if volume > 0
            if (clampedVolume > 0) {
                set({ muted: false });
                storage_1.default.setItem(MUTED_STORAGE_KEY, "false").catch(console.error);
            }
            storage_1.default
                .setItem(VOLUME_STORAGE_KEY, clampedVolume.toString())
                .catch(console.error);
        },
        setMuted: (muted) => {
            set({ muted });
            storage_1.default.setItem(MUTED_STORAGE_KEY, muted.toString()).catch(console.error);
        },
        // Danmu settings - start with defaults
        danmuUnlocked: false,
        danmuEnabled: false,
        danmuOpacity: 80,
        danmuSpeed: 1,
        danmuLaneCount: 12,
        danmuMaxMessages: 50,
        setDanmuUnlocked: (unlocked) => {
            set({ danmuUnlocked: unlocked });
            storage_1.default
                .setItem(DANMU_UNLOCKED_KEY, unlocked.toString())
                .catch(console.error);
        },
        setDanmuEnabled: (enabled) => {
            set({ danmuEnabled: enabled });
            storage_1.default
                .setItem(DANMU_ENABLED_KEY, enabled.toString())
                .catch(console.error);
        },
        setDanmuOpacity: (opacity) => {
            const clamped = Math.max(0, Math.min(100, opacity));
            set({ danmuOpacity: clamped });
            storage_1.default
                .setItem(DANMU_OPACITY_KEY, clamped.toString())
                .catch(console.error);
        },
        setDanmuSpeed: (speed) => {
            const clamped = Math.max(0.1, Math.min(3, speed));
            set({ danmuSpeed: clamped });
            storage_1.default.setItem(DANMU_SPEED_KEY, clamped.toString()).catch(console.error);
        },
        setDanmuLaneCount: (laneCount) => {
            const clamped = Math.max(4, Math.min(20, laneCount));
            set({ danmuLaneCount: clamped });
            storage_1.default
                .setItem(DANMU_LANE_COUNT_KEY, clamped.toString())
                .catch(console.error);
        },
        setDanmuMaxMessages: (maxMessages) => {
            const clamped = Math.max(5, Math.min(200, maxMessages));
            set({ danmuMaxMessages: clamped });
            storage_1.default
                .setItem(DANMU_MAX_MESSAGES_KEY, clamped.toString())
                .catch(console.error);
        },
    }));
    // Load initial volume and danmu state from storage asynchronously
    (async () => {
        try {
            const storedVolume = await storage_1.default.getItem(VOLUME_STORAGE_KEY);
            const storedMuted = await storage_1.default.getItem(MUTED_STORAGE_KEY);
            const storedDanmuUnlocked = await storage_1.default.getItem(DANMU_UNLOCKED_KEY);
            const storedDanmuEnabled = await storage_1.default.getItem(DANMU_ENABLED_KEY);
            const storedDanmuOpacity = await storage_1.default.getItem(DANMU_OPACITY_KEY);
            const storedDanmuSpeed = await storage_1.default.getItem(DANMU_SPEED_KEY);
            const storedDanmuLaneCount = await storage_1.default.getItem(DANMU_LANE_COUNT_KEY);
            const storedDanmuMaxMessages = await storage_1.default.getItem(DANMU_MAX_MESSAGES_KEY);
            let initialVolume = 1.0;
            let initialMuted = false;
            let initialDanmuUnlocked = false;
            let initialDanmuEnabled = false;
            let initialDanmuOpacity = 80;
            let initialDanmuSpeed = 1;
            let initialDanmuLaneCount = 12;
            let initialDanmuMaxMessages = 50;
            if (storedVolume) {
                const parsedVolume = parseFloat(storedVolume);
                if (Number.isFinite(parsedVolume) &&
                    parsedVolume >= 0 &&
                    parsedVolume <= 1) {
                    initialVolume = parsedVolume;
                }
            }
            if (storedMuted) {
                initialMuted = storedMuted === "true";
            }
            if (storedDanmuUnlocked) {
                initialDanmuUnlocked = storedDanmuUnlocked === "true";
            }
            if (storedDanmuEnabled) {
                initialDanmuEnabled = storedDanmuEnabled === "true";
            }
            if (storedDanmuOpacity) {
                const parsed = parseInt(storedDanmuOpacity);
                if (Number.isFinite(parsed) && parsed >= 0 && parsed <= 100) {
                    initialDanmuOpacity = parsed;
                }
            }
            if (storedDanmuSpeed) {
                const parsed = parseFloat(storedDanmuSpeed);
                if (Number.isFinite(parsed) && parsed >= 0.1 && parsed <= 3) {
                    initialDanmuSpeed = parsed;
                }
            }
            if (storedDanmuLaneCount) {
                const parsed = parseInt(storedDanmuLaneCount);
                if (Number.isFinite(parsed) && parsed >= 4 && parsed <= 20) {
                    initialDanmuLaneCount = parsed;
                }
            }
            if (storedDanmuMaxMessages) {
                const parsed = parseInt(storedDanmuMaxMessages);
                if (Number.isFinite(parsed) && parsed >= 5 && parsed <= 200) {
                    initialDanmuMaxMessages = parsed;
                }
            }
            store.setState({
                volume: initialVolume,
                muted: initialMuted,
                danmuUnlocked: initialDanmuUnlocked,
                danmuEnabled: initialDanmuEnabled,
                danmuOpacity: initialDanmuOpacity,
                danmuSpeed: initialDanmuSpeed,
                danmuLaneCount: initialDanmuLaneCount,
                danmuMaxMessages: initialDanmuMaxMessages,
            });
        }
        catch (error) {
            console.error("Failed to load state from storage:", error);
        }
    })();
    return store;
};
exports.makeStreamplaceStore = makeStreamplaceStore;
function getStreamplaceStoreFromContext() {
    const context = (0, react_1.useContext)(context_1.StreamplaceContext);
    if (!context) {
        throw new Error("useStreamplaceStore must be used within a StreamplaceProvider");
    }
    return context.store;
}
function useStreamplaceStore(selector) {
    return (0, zustand_1.useStore)(getStreamplaceStoreFromContext(), selector);
}
const useUrl = () => useStreamplaceStore((x) => x.url);
exports.useUrl = useUrl;
const useDID = () => useStreamplaceStore((x) => x.oauthSession?.did);
exports.useDID = useDID;
const useHandle = () => useStreamplaceStore((x) => x.handle);
exports.useHandle = useHandle;
const useSetHandle = () => {
    const store = getStreamplaceStoreFromContext();
    return (handle) => store.setState({ handle });
};
exports.useSetHandle = useSetHandle;
// Content metadata hooks
const useContentMetadata = () => useStreamplaceStore((x) => x.contentMetadata);
exports.useContentMetadata = useContentMetadata;
const useSetContentMetadata = () => {
    const store = getStreamplaceStoreFromContext();
    return (metadata) => store.setState({ contentMetadata: metadata });
};
exports.useSetContentMetadata = useSetContentMetadata;
// Volume/muted hooks
const useVolume = () => useStreamplaceStore((x) => x.volume);
exports.useVolume = useVolume;
const useMuted = () => useStreamplaceStore((x) => x.muted);
exports.useMuted = useMuted;
const useSetVolume = () => useStreamplaceStore((x) => x.setVolume);
exports.useSetVolume = useSetVolume;
const useSetMuted = () => useStreamplaceStore((x) => x.setMuted);
exports.useSetMuted = useSetMuted;
// Composite hook for effective volume (0 if muted) - used by video components
const useEffectiveVolume = () => useStreamplaceStore((state) => {
    const effectiveVolume = state.muted ? 0 : state.volume;
    // Ensure we always return a finite number for HTMLMediaElement.volume
    return Number.isFinite(effectiveVolume) ? effectiveVolume : 1.0;
});
exports.useEffectiveVolume = useEffectiveVolume;
// Danmu convenience hooks
const useDanmuUnlocked = () => useStreamplaceStore((x) => x.danmuUnlocked);
exports.useDanmuUnlocked = useDanmuUnlocked;
const useDanmuEnabled = () => useStreamplaceStore((x) => x.danmuEnabled);
exports.useDanmuEnabled = useDanmuEnabled;
const useDanmuOpacity = () => useStreamplaceStore((x) => x.danmuOpacity);
exports.useDanmuOpacity = useDanmuOpacity;
const useDanmuSpeed = () => useStreamplaceStore((x) => x.danmuSpeed);
exports.useDanmuSpeed = useDanmuSpeed;
const useDanmuLaneCount = () => useStreamplaceStore((x) => x.danmuLaneCount);
exports.useDanmuLaneCount = useDanmuLaneCount;
const useDanmuMaxMessages = () => useStreamplaceStore((x) => x.danmuMaxMessages);
exports.useDanmuMaxMessages = useDanmuMaxMessages;
const useSetDanmuUnlocked = () => useStreamplaceStore((x) => x.setDanmuUnlocked);
exports.useSetDanmuUnlocked = useSetDanmuUnlocked;
const useSetDanmuEnabled = () => useStreamplaceStore((x) => x.setDanmuEnabled);
exports.useSetDanmuEnabled = useSetDanmuEnabled;
const useSetDanmuOpacity = () => useStreamplaceStore((x) => x.setDanmuOpacity);
exports.useSetDanmuOpacity = useSetDanmuOpacity;
const useSetDanmuSpeed = () => useStreamplaceStore((x) => x.setDanmuSpeed);
exports.useSetDanmuSpeed = useSetDanmuSpeed;
const useSetDanmuLaneCount = () => useStreamplaceStore((x) => x.setDanmuLaneCount);
exports.useSetDanmuLaneCount = useSetDanmuLaneCount;
const useSetDanmuMaxMessages = () => useStreamplaceStore((x) => x.setDanmuMaxMessages);
exports.useSetDanmuMaxMessages = useSetDanmuMaxMessages;
// Composite hook that calls all individual hooks
const useDanmuSettings = () => {
    const danmuUnlocked = (0, exports.useDanmuUnlocked)();
    const danmuEnabled = (0, exports.useDanmuEnabled)();
    const danmuOpacity = (0, exports.useDanmuOpacity)();
    const danmuSpeed = (0, exports.useDanmuSpeed)();
    const danmuLaneCount = (0, exports.useDanmuLaneCount)();
    const danmuMaxMessages = (0, exports.useDanmuMaxMessages)();
    const setDanmuUnlocked = (0, exports.useSetDanmuUnlocked)();
    const setDanmuEnabled = (0, exports.useSetDanmuEnabled)();
    const setDanmuOpacity = (0, exports.useSetDanmuOpacity)();
    const setDanmuSpeed = (0, exports.useSetDanmuSpeed)();
    const setDanmuLaneCount = (0, exports.useSetDanmuLaneCount)();
    const setDanmuMaxMessages = (0, exports.useSetDanmuMaxMessages)();
    return {
        danmuUnlocked,
        danmuEnabled,
        danmuOpacity,
        danmuSpeed,
        danmuLaneCount,
        danmuMaxMessages,
        setDanmuUnlocked,
        setDanmuEnabled,
        setDanmuOpacity,
        setDanmuSpeed,
        setDanmuLaneCount,
        setDanmuMaxMessages,
    };
};
exports.useDanmuSettings = useDanmuSettings;
//# sourceMappingURL=streamplace-store.js.map