(function() {
    'use strict';

    let currentBackgroundStyle = null;

    function loadImageAsDataURL(url) {
        return new Promise((resolve, reject) => {
            chrome.runtime.sendMessage({ action: 'fetchImage', url }, (response) => {
                if (response.error) {
                    reject(new Error(response.error));
                } else {
                    resolve(response.dataUrl);
                }
            });
        });
    }

    async function updateBackground(url, blur) {
        if (currentBackgroundStyle) {
            currentBackgroundStyle.remove();
            currentBackgroundStyle = null;
        }

        if (!url || url.trim() === '') {
            disableBackground();
            return;
        }

        try {
            const dataUrl = await loadImageAsDataURL(url);

            const style = document.createElement('style');
            style.id = 'ishak-custom-background';
            style.textContent = `
                body {
                    position: relative;
                    background: transparent !important;
                }
                body::before {
                    content: "";
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background-image: url('${dataUrl}');
                    background-size: cover;
                    background-position: center;
                    background-repeat: no-repeat;
                    filter: blur(${blur}px);
                    z-index: -1;
                    pointer-events: none;
                }
            `;
            document.head.appendChild(style);
            currentBackgroundStyle = style;

            localStorage.setItem('customBackgroundUrl', url);
            localStorage.setItem('customBackgroundBlur', blur);
            localStorage.setItem('customBackgroundEnabled', 'true');
        } catch (error) {
            console.error('Ошибка загрузки изображения:', error);
            alert('Не удалось загрузить изображение. Проверьте ссылку или попробуйте другую.');
            disableBackground();
        }
    }

    function disableBackground() {
        if (currentBackgroundStyle) {
            currentBackgroundStyle.remove();
            currentBackgroundStyle = null;
        }
        localStorage.setItem('customBackgroundEnabled', 'false');
    }

    function loadBackgroundSettings() {
        const enabled = localStorage.getItem('customBackgroundEnabled') === 'true';
        const url = localStorage.getItem('customBackgroundUrl') || '';
        const blur = parseFloat(localStorage.getItem('customBackgroundBlur')) || 0;
        return { enabled, url, blur };
    }

    async function initBackground() {
        const { enabled, url, blur } = loadBackgroundSettings();
        if (enabled && url) {
            await updateBackground(url, blur);
        }
    }

    window.enableBackground = updateBackground;
    window.disableBackground = disableBackground;
    window.loadBackgroundSettings = loadBackgroundSettings;
    window.initBackground = initBackground;
})();