// Психоделические эффекты — два режима: light и heavy
let currentMode = 'off'; // 'off', 'light', 'heavy'

// Элементы эффектов
let cursorCanvas = null;
let ctxCursor = null;
let mistLayer = null;
let heavyCanvas = null; // дополнительный слой для тяжёлого режима
let animationFrame = null;
let hideCursorStyle = null;

// Параметры для режимов
let trailPositions = [];
let trailLength = 60;
let trailMaxAge = 800;
let rotationSpeed = 0.02;
let heavyParams = {
    hueShift: 0,
    brightness: 1,
    contrast: 1,
    time: 0
};

// Летающие ишаки
let floatingDonkeys = [];
const DONKEY_COUNT = 15;

let lastMouseX = 0, lastMouseY = 0;
let rotationAngle = 0;

// Загрузка/сохранение режима
function savePsychedelicMode(mode) {
    localStorage.setItem('psychedelicMode', mode);
    currentMode = mode;
}

function loadPsychedelicMode() {
    return localStorage.getItem('psychedelicMode') || 'off';
}

// Очистка всех созданных элементов
function removeAllEffects() {
    if (hideCursorStyle) {
        hideCursorStyle.remove();
        hideCursorStyle = null;
    }
    if (cursorCanvas) {
        cursorCanvas.remove();
        cursorCanvas = null;
        ctxCursor = null;
        document.removeEventListener('mousemove', onMouseMove);
    }
    if (mistLayer) {
        mistLayer.remove();
        mistLayer = null;
    }
    if (heavyCanvas) {
        heavyCanvas.remove();
        heavyCanvas = null;
    }
    if (animationFrame) {
        cancelAnimationFrame(animationFrame);
        animationFrame = null;
    }
    trailPositions = [];
    floatingDonkeys = [];
    rotationAngle = 0;
    document.documentElement.style.filter = '';
    document.body.style.filter = '';
}

// Общий обработчик движения мыши
function onMouseMove(e) {
    lastMouseX = e.clientX;
    lastMouseY = e.clientY;
    trailPositions.push({ x: lastMouseX, y: lastMouseY, time: performance.now() });
    if (trailPositions.length > trailLength) {
        trailPositions.shift();
    }
}

// Рисование курсора (общее для обоих режимов)
function drawCursor() {
    if (!ctxCursor || !cursorCanvas) return;

    ctxCursor.clearRect(0, 0, window.innerWidth, window.innerHeight);

    const now = performance.now();
    trailPositions.forEach((pos, index) => {
        const age = now - pos.time;
        let opacity = 1 - (age / trailMaxAge);
        if (opacity < 0) opacity = 0;
        if (opacity === 0) return;

        const hue = (Date.now() / 10 + index * 15) % 360;
        ctxCursor.fillStyle = `hsla(${hue}, 100%, 50%, ${opacity * 0.7})`;

        const size = 22;
        const angle = rotationAngle + index * 0.1;
        ctxCursor.save();
        ctxCursor.translate(pos.x, pos.y);
        ctxCursor.rotate(angle);
        ctxCursor.beginPath();
        ctxCursor.moveTo(0, -size / 2);
        ctxCursor.lineTo(-size / 2, size / 2);
        ctxCursor.lineTo(size / 2, size / 2);
        ctxCursor.closePath();
        ctxCursor.fill();
        ctxCursor.restore();
    });

    if (lastMouseX && lastMouseY) {
        const hue = (Date.now() / 10) % 360;
        ctxCursor.fillStyle = `hsl(${hue}, 100%, 50%)`;
        const size = 26;
        ctxCursor.save();
        ctxCursor.translate(lastMouseX, lastMouseY);
        ctxCursor.rotate(rotationAngle);
        ctxCursor.beginPath();
        ctxCursor.moveTo(0, -size / 2);
        ctxCursor.lineTo(-size / 2, size / 2);
        ctxCursor.lineTo(size / 2, size / 2);
        ctxCursor.closePath();
        ctxCursor.fill();
        ctxCursor.restore();
    }

    rotationAngle += rotationSpeed;
}

// Создание летающих ишаков
function createDonkeys() {
    const donkeyImageSrc = chrome.runtime.getURL('logos/Ishak.png');
    floatingDonkeys = [];
    for (let i = 0; i < DONKEY_COUNT; i++) {
        floatingDonkeys.push({
            x: Math.random() * window.innerWidth,
            y: Math.random() * window.innerHeight,
            vx: (Math.random() - 0.5) * 1.5,
            vy: (Math.random() - 0.5) * 1.5,
            size: Math.random() * 70 + 50,
            opacity: Math.random() * 0.2 + 0.1,
            angle: Math.random() * Math.PI * 2,
            rotationSpeed: (Math.random() - 0.5) * 0.02,
            img: new Image(),
            loaded: false
        });
        const donkey = floatingDonkeys[i];
        donkey.img.onload = () => donkey.loaded = true;
        donkey.img.src = donkeyImageSrc;
    }
}

// Рисование эффектов heavy-режима (искажения, линзы, полосы, ишаки)
function drawHeavyEffects() {
    if (!heavyCanvas) return;
    const ctx = heavyCanvas.getContext('2d');
    const w = window.innerWidth;
    const h = window.innerHeight;
    ctx.clearRect(0, 0, w, h);

    const time = heavyParams.time;

    // Волновые искажения
    ctx.globalAlpha = 0.2;
    for (let i = 0; i < 5; i++) {
        const yOffset = Math.sin(time * 0.005 + i) * 50;
        ctx.fillStyle = `hsla(${ (time + i*30) % 360 }, 80%, 60%, 0.1)`;
        ctx.beginPath();
        ctx.arc(w/2 + Math.sin(time*0.003 + i)*100, h/2 + yOffset, 150, 0, Math.PI*2);
        ctx.fill();
    }

    // Цветные линзы вокруг курсора
    if (lastMouseX && lastMouseY) {
        ctx.globalAlpha = 0.25;
        for (let i = 0; i < 3; i++) {
            const hue = (time + i*120) % 360;
            ctx.fillStyle = `hsla(${hue}, 100%, 60%, 0.2)`;
            ctx.beginPath();
            ctx.arc(
                lastMouseX + Math.sin(time*0.01 + i)*40,
                lastMouseY + Math.cos(time*0.01 + i)*40,
                70 + i*20, 0, Math.PI*2
            );
            ctx.fill();
        }
    }

    // Мерцающие полосы
    ctx.globalAlpha = 0.1;
    for (let i = 0; i < 8; i++) {
        const x = (time * 0.1 + i * 120) % (w + 200) - 100;
        ctx.fillStyle = `hsla(${ (time + i*40) % 360 }, 100%, 70%, 0.1)`;
        ctx.fillRect(x, 0, 40, h);
    }

    // Рисуем ишаков
    floatingDonkeys.forEach(d => {
        if (!d.loaded) return;
        d.x += d.vx;
        d.y += d.vy;
        d.angle += d.rotationSpeed;

        if (d.x < -d.size) d.x = w + d.size;
        if (d.x > w + d.size) d.x = -d.size;
        if (d.y < -d.size) d.y = h + d.size;
        if (d.y > h + d.size) d.y = -d.size;

        ctx.globalAlpha = d.opacity;
        ctx.save();
        ctx.translate(d.x, d.y);
        ctx.rotate(d.angle);
        ctx.drawImage(d.img, -d.size/2, -d.size/2, d.size, d.size);
        ctx.restore();
    });
    ctx.globalAlpha = 1.0;
}

// Анимация (общая)
function animate() {
    heavyParams.time = performance.now();

    // Применяем CSS-фильтры к документу в heavy-режиме
    if (currentMode === 'heavy') {
        heavyParams.hueShift = (heavyParams.hueShift + 0.6) % 360;
        // Уменьшена амплитуда яркости и контраста
        heavyParams.brightness = 1 + Math.sin(heavyParams.time * 0.003) * 0.15;
        heavyParams.contrast = 1 + Math.sin(heavyParams.time * 0.002) * 0.2;
        document.documentElement.style.filter = `
            hue-rotate(${heavyParams.hueShift}deg)
            brightness(${heavyParams.brightness})
            contrast(${heavyParams.contrast})
        `;
    }

    drawCursor();
    if (currentMode === 'heavy' && heavyCanvas) {
        drawHeavyEffects();
    }
    animationFrame = requestAnimationFrame(animate);
}

// Включение режима light
function enableLightMode() {
    if (!hideCursorStyle) {
        hideCursorStyle = document.createElement('style');
        hideCursorStyle.id = 'psychedelic-hide-cursor';
        hideCursorStyle.textContent = '* { cursor: none !important; }';
        document.head.appendChild(hideCursorStyle);
    }

    if (!cursorCanvas) {
        cursorCanvas = document.createElement('canvas');
        cursorCanvas.id = 'psychedelic-cursor-canvas';
        cursorCanvas.style.position = 'fixed';
        cursorCanvas.style.top = '0';
        cursorCanvas.style.left = '0';
        cursorCanvas.style.width = '100%';
        cursorCanvas.style.height = '100%';
        cursorCanvas.style.pointerEvents = 'none';
        cursorCanvas.style.zIndex = '10003';
        document.body.appendChild(cursorCanvas);
        cursorCanvas.width = window.innerWidth;
        cursorCanvas.height = window.innerHeight;
        ctxCursor = cursorCanvas.getContext('2d');
        document.addEventListener('mousemove', onMouseMove);
    }

    if (!mistLayer) {
        mistLayer = document.createElement('div');
        mistLayer.id = 'psychedelic-mist';
        mistLayer.style.position = 'fixed';
        mistLayer.style.top = '0';
        mistLayer.style.left = '0';
        mistLayer.style.width = '100%';
        mistLayer.style.height = '100%';
        mistLayer.style.pointerEvents = 'none';
        mistLayer.style.zIndex = '9996';
        mistLayer.style.background = 'radial-gradient(circle at 20% 50%, rgba(255,0,255,0.6), rgba(0,255,255,0.6), rgba(255,255,0,0.6))';
        mistLayer.style.animation = 'psychedelicMist 8s infinite alternate';
        mistLayer.style.mixBlendMode = 'overlay';
        document.body.appendChild(mistLayer);
    }

    if (heavyCanvas) {
        heavyCanvas.remove();
        heavyCanvas = null;
    }

    if (!animationFrame) {
        animate();
    }

    window.addEventListener('resize', onResize);
}

// Включение режима heavy (усиленный)
function enableHeavyMode() {
    enableLightMode();

    trailLength = 120;
    trailMaxAge = 1500;
    rotationSpeed = 0.04;

    if (mistLayer) {
        mistLayer.style.background = 'radial-gradient(circle at 20% 50%, rgba(255,0,255,0.9), rgba(0,255,255,0.9), rgba(255,255,0,0.9))';
        mistLayer.style.animation = 'psychedelicMist 3s infinite alternate';
    }

    if (!heavyCanvas) {
        heavyCanvas = document.createElement('canvas');
        heavyCanvas.id = 'psychedelic-heavy-canvas';
        heavyCanvas.style.position = 'fixed';
        heavyCanvas.style.top = '0';
        heavyCanvas.style.left = '0';
        heavyCanvas.style.width = '100%';
        heavyCanvas.style.height = '100%';
        heavyCanvas.style.pointerEvents = 'none';
        heavyCanvas.style.zIndex = '9998';
        document.body.appendChild(heavyCanvas);
        heavyCanvas.width = window.innerWidth;
        heavyCanvas.height = window.innerHeight;
    }

    createDonkeys();

    heavyParams = {
        hueShift: 0,
        brightness: 1,
        contrast: 1,
        time: performance.now()
    };

    window.addEventListener('resize', onResize);
}

function onResize() {
    if (cursorCanvas) {
        cursorCanvas.width = window.innerWidth;
        cursorCanvas.height = window.innerHeight;
    }
    if (heavyCanvas) {
        heavyCanvas.width = window.innerWidth;
        heavyCanvas.height = window.innerHeight;
    }
}

function setPsychedelicMode(mode) {
    if (mode === currentMode) {
        removeAllEffects();
        savePsychedelicMode('off');
        return;
    }

    removeAllEffects();

    trailLength = 60;
    trailMaxAge = 800;
    rotationSpeed = 0.02;

    if (mode === 'light') {
        enableLightMode();
        savePsychedelicMode('light');
    } else if (mode === 'heavy') {
        enableHeavyMode();
        savePsychedelicMode('heavy');
    } else {
        savePsychedelicMode('off');
    }
}

function initPsychedelic() {
    const savedMode = loadPsychedelicMode();
    if (savedMode !== 'off') {
        setPsychedelicMode(savedMode);
    }
}

window.setPsychedelicMode = setPsychedelicMode;
window.loadPsychedelicMode = loadPsychedelicMode;
window.initPsychedelic = initPsychedelic;

if (!document.querySelector('#psychedelic-keyframes')) {
    const style = document.createElement('style');
    style.id = 'psychedelic-keyframes';
    style.textContent = `
        @keyframes psychedelicMist {
            0% { opacity: 0.8; filter: hue-rotate(0deg) blur(3px); }
            50% { opacity: 1; filter: hue-rotate(180deg) blur(5px); }
            100% { opacity: 0.8; filter: hue-rotate(360deg) blur(3px); }
        }
    `;
    document.head.appendChild(style);
}