"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useFetchBroadcasterDID = useFetchBroadcasterDID;
exports.useFetchEnvConfig = useFetchEnvConfig;
exports.useFetchBranding = useFetchBranding;
exports.useBrandingAsset = useBrandingAsset;
exports.useMainLogo = useMainLogo;
exports.useFavicon = useFavicon;
exports.useSiteTitle = useSiteTitle;
exports.useSiteDescription = useSiteDescription;
exports.usePrimaryColor = usePrimaryColor;
exports.useAccentColor = useAccentColor;
exports.useDefaultStreamer = useDefaultStreamer;
exports.useSidebarBackgroundImage = useSidebarBackgroundImage;
exports.useLegalLinks = useLegalLinks;
exports.useBrandingAutoFetch = useBrandingAutoFetch;
const tslib_1 = require("tslib");
const react_1 = require("react");
const storage_1 = tslib_1.__importDefault(require("../storage"));
const streamplace_store_1 = require("./streamplace-store");
const xrpc_1 = require("./xrpc");
// helper to convert blob to base64
const blobToBase64 = (blob) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(blob);
    });
};
const PropsInHeader = [
    "siteTitle",
    "siteDescription",
    "primaryColor",
    "accentColor",
    "defaultStreamer",
    "mainLogo",
    "favicon",
    "sidebarBg",
    "legalLinks",
];
function getMetaContent(key) {
    if (typeof window === "undefined" || !window.document)
        return null;
    const meta = document.querySelector(`meta[name="internal-brand:${key}`);
    if (meta && meta.getAttribute("content")) {
        let content = meta.getAttribute("content");
        if (content)
            return JSON.parse(content);
    }
    return null;
}
// hook to fetch broadcaster DID (unauthenticated)
function useFetchBroadcasterDID() {
    const streamplaceAgent = (0, xrpc_1.usePossiblyUnauthedPDSAgent)();
    const store = (0, streamplace_store_1.getStreamplaceStoreFromContext)();
    // prefetch from meta records, if on web
    (0, react_1.useEffect)(() => {
        if (typeof window !== "undefined" && window.document) {
            try {
                const metaRecords = PropsInHeader.reduce((acc, key) => {
                    const meta = document.querySelector(`meta[name="internal-brand:${key}`);
                    // hrmmmmmmmmmmmm
                    if (meta && meta.getAttribute("content")) {
                        let content = meta.getAttribute("content");
                        if (content)
                            acc[key] = JSON.parse(content);
                    }
                    return acc;
                }, {});
                console.log("Found meta records for broadcaster DID:", metaRecords);
                // filter out all non-text values, can get on second fetch?
                for (const key of Object.keys(metaRecords)) {
                    if (metaRecords[key].mimeType != "text/plain") {
                        delete metaRecords[key];
                    }
                }
            }
            catch (e) {
                console.warn("Failed to parse broadcaster DID from meta tags", e);
            }
        }
    }, []);
    return (0, react_1.useCallback)(async () => {
        try {
            if (!streamplaceAgent) {
                throw new Error("Streamplace agent not available");
            }
            const result = await streamplaceAgent.place.stream.broadcast.getBroadcaster();
            store.setState({ broadcasterDID: result.data.broadcaster });
            if (result.data.server) {
                store.setState({ serverDID: result.data.server });
            }
            if (result.data.admins) {
                store.setState({ adminDIDs: result.data.admins });
            }
        }
        catch (err) {
            console.error("Failed to fetch broadcaster DID:", err);
        }
    }, [streamplaceAgent, store]);
}
// hook to fetch client-facing env config from the server
function useFetchEnvConfig() {
    const streamplaceAgent = (0, xrpc_1.usePossiblyUnauthedPDSAgent)();
    const store = (0, streamplace_store_1.getStreamplaceStoreFromContext)();
    return (0, react_1.useCallback)(async () => {
        try {
            if (!streamplaceAgent) {
                throw new Error("Streamplace agent not available");
            }
            const result = await streamplaceAgent.place.stream.config.getEnv();
            if (result.data.playbackWorkerUrl) {
                store.setState({ playbackWorkerUrl: result.data.playbackWorkerUrl });
            }
            store.setState({ gamesEnabled: result.data.gamesEnabled ?? false });
        }
        catch (err) {
            console.error("Failed to fetch env config:", err);
        }
    }, [streamplaceAgent, store]);
}
// hook to fetch branding data from the server
function useFetchBranding() {
    const streamplaceAgent = (0, xrpc_1.usePossiblyUnauthedPDSAgent)();
    const broadcasterDID = (0, streamplace_store_1.useStreamplaceStore)((state) => state.broadcasterDID);
    const url = (0, streamplace_store_1.useStreamplaceStore)((state) => state.url);
    const store = (0, streamplace_store_1.getStreamplaceStoreFromContext)();
    return (0, react_1.useCallback)(async ({ force = true } = {}) => {
        if (!broadcasterDID)
            return;
        try {
            store.setState({ brandingLoading: true });
            // check localStorage first
            const cacheKey = `branding:${broadcasterDID}`;
            const cached = await storage_1.default.getItem(cacheKey);
            if (!force && cached) {
                try {
                    const parsed = JSON.parse(cached);
                    // check if cache is less than 1 hour old
                    if (Date.now() - parsed.timestamp < 60 * 60 * 1000) {
                        store.setState({
                            branding: parsed.data,
                            brandingLoading: false,
                            brandingError: null,
                        });
                        return;
                    }
                }
                catch (e) {
                    // invalid cache, continue to fetch
                    console.warn("Invalid branding cache, refetching", e);
                }
            }
            // fetch branding metadata from server
            if (!streamplaceAgent) {
                throw new Error("Streamplace agent not available");
            }
            const res = await streamplaceAgent.place.stream.branding.getBranding({
                broadcaster: broadcasterDID,
            });
            const assets = res.data.assets;
            // convert assets array to keyed object and fetch blob data
            const brandingMap = {};
            for (const asset of assets) {
                brandingMap[asset.key] = { ...asset };
                // if data is already inline (text assets), use it directly
                if (asset.data) {
                    brandingMap[asset.key].data = asset.data;
                }
                else if (asset.url) {
                    // for images, construct full URL and fetch blob
                    const fullUrl = `${url}${asset.url}`;
                    const blobRes = await fetch(fullUrl);
                    const blob = await blobRes.blob();
                    brandingMap[asset.key].data = await blobToBase64(blob);
                }
            }
            // cache in localStorage
            storage_1.default.setItem(cacheKey, JSON.stringify({
                timestamp: Date.now(),
                data: brandingMap,
            }));
            store.setState({
                branding: brandingMap,
                brandingLoading: false,
                brandingError: null,
            });
        }
        catch (err) {
            console.error("Failed to fetch branding:", err);
            store.setState({
                brandingLoading: false,
                brandingError: err.message || "Failed to fetch branding",
            });
        }
    }, [broadcasterDID, streamplaceAgent, url, store]);
}
// hook to get a specific branding asset by key
function useBrandingAsset(key) {
    return ((0, streamplace_store_1.useStreamplaceStore)((state) => state.branding?.[key]) ||
        getMetaContent(key) ||
        undefined);
}
// convenience hook for main logo
function useMainLogo() {
    const asset = useBrandingAsset("mainLogo");
    return asset?.data;
}
// convenience hook for favicon
function useFavicon() {
    const asset = useBrandingAsset("favicon");
    return asset?.data;
}
// convenience hook for site title
function useSiteTitle() {
    const asset = useBrandingAsset("siteTitle");
    return asset?.data || "My Streamplace Station";
}
// convenience hook for site description
function useSiteDescription() {
    const asset = useBrandingAsset("siteDescription");
    return asset?.data || "Live streaming platform";
}
// convenience hook for primary color
function usePrimaryColor() {
    const asset = useBrandingAsset("primaryColor");
    return asset?.data || "#6366f1";
}
// convenience hook for accent color
function useAccentColor() {
    const asset = useBrandingAsset("accentColor");
    return asset?.data || "#8b5cf6";
}
// convenience hook for default streamer
function useDefaultStreamer() {
    const asset = useBrandingAsset("defaultStreamer");
    return asset?.data || undefined;
}
// convenience hook for sidebar background image
function useSidebarBackgroundImage() {
    return useBrandingAsset("sidebarBackgroundImage");
}
// convenience hook for legal links
function useLegalLinks() {
    const asset = useBrandingAsset("legalLinks");
    if (!asset?.data) {
        return [];
    }
    try {
        return JSON.parse(asset.data);
    }
    catch {
        return [];
    }
}
// hook to auto-fetch branding when broadcaster changes
function useBrandingAutoFetch() {
    const fetchBranding = useFetchBranding();
    const broadcasterDID = (0, streamplace_store_1.useStreamplaceStore)((state) => state.broadcasterDID);
    (0, react_1.useEffect)(() => {
        if (broadcasterDID) {
            fetchBranding();
        }
    }, [broadcasterDID, fetchBranding]);
}
//# sourceMappingURL=branding.js.map