/* Minification failed. Returning unminified contents.
(13,31-32): run-time error JS1195: Expected expression: >
(13,55-56): run-time error JS1004: Expected ';': )
(21,34-35): run-time error JS1195: Expected expression: )
(21,37-38): run-time error JS1195: Expected expression: >
(51,48-49): run-time error JS1195: Expected expression: )
(51,51-52): run-time error JS1195: Expected expression: >
(52,20-21): run-time error JS1195: Expected expression: )
(52,23-24): run-time error JS1195: Expected expression: >
(57,5-6): run-time error JS1002: Syntax error: }
(60,55-56): run-time error JS1004: Expected ';': {
(65,2-3): run-time error JS1195: Expected expression: )
(67,23-24): run-time error JS1004: Expected ';': {
(115,20-21): run-time error JS1195: Expected expression: )
(115,23-24): run-time error JS1195: Expected expression: >
(137,6-7): run-time error JS1195: Expected expression: )
(160,28-29): run-time error JS1014: Invalid character: `
(160,35-36): run-time error JS1193: Expected ',' or ')': :
(160,44-45): run-time error JS1014: Invalid character: `
(160,45-46): run-time error JS1195: Expected expression: )
(197,56-57): run-time error JS1195: Expected expression: >
(197,80-81): run-time error JS1004: Expected ';': )
(232,43-44): run-time error JS1195: Expected expression: >
(235,6-7): run-time error JS1195: Expected expression: )
(240,43-44): run-time error JS1195: Expected expression: >
(243,6-7): run-time error JS1195: Expected expression: )
(249,56-57): run-time error JS1195: Expected expression: >
(249,80-81): run-time error JS1004: Expected ';': )
(281,65-66): run-time error JS1195: Expected expression: >
(283,10-11): run-time error JS1195: Expected expression: )
(286,52-53): run-time error JS1195: Expected expression: >
(290,10-11): run-time error JS1195: Expected expression: )
(335,30-31): run-time error JS1014: Invalid character: `
(335,32-33): run-time error JS1004: Expected ';': {
(335,54-55): run-time error JS1014: Invalid character: `
(363,25-26): run-time error JS1014: Invalid character: `
(363,27-28): run-time error JS1004: Expected ';': {
(363,46-47): run-time error JS1014: Invalid character: `
(366,28-29): run-time error JS1014: Invalid character: `
(366,30-31): run-time error JS1004: Expected ';': {
(366,49-50): run-time error JS1014: Invalid character: `
(369,28-29): run-time error JS1014: Invalid character: `
(369,30-31): run-time error JS1004: Expected ';': {
(369,49-50): run-time error JS1014: Invalid character: `
(372,31-32): run-time error JS1014: Invalid character: `
(372,33-34): run-time error JS1004: Expected ';': {
(372,73-74): run-time error JS1014: Invalid character: `
(425,32-33): run-time error JS1195: Expected expression: >
(443,10-11): run-time error JS1195: Expected expression: )
(445,9-17): run-time error JS1197: Too many errors. The file might not be a JavaScript file: document
(418,1-24): run-time error JS1301: End of file encountered before function is properly closed: function removeImages()
(445,17-18): run-time error JS1195: Expected expression: .
(445,18-34): run-time error JS1197: Too many errors. The file might not be a JavaScript file: querySelectorAll
(68,16-22): run-time error JS1018: 'return' statement outside of function: return
 */
let state = {};
let isScreenReaderActive = false;

const readingGuide = document.querySelector(".reading-guide");
const readingMask = document.querySelector(".reading-mask");
const menu = document.querySelector(".acc-menu");
const menuButton = document.querySelector(".acc-menu-button");

// Türkçe konuşma paketi destekleniyor mu kontrolü
function isTurkishVoiceAvailable() {
    const voices = synth.getVoices();
    
    return voices.some(voice => voice.lang === 'tr-TR');
}

// Seslerin yüklenmesini beklemek
function waitForVoices(callback) {
    if (synth.getVoices().length > 0) {
        callback();
    } else {
        synth.onvoiceschanged = () => {
            callback();
        };
    }
}

// Ekran Okuyucu butonunu pasif yap
function disableScreenReaderButton() {
    const button = document.getElementById("screenReaderToggleButton");
    const errorSpan = document.getElementById("screen-reader-error");
    const tooltip = document.getElementById("screenReaderTooltip");

    alert("Türkçe konuşma dil desteği bulunamadığı için işlem gerçekleştirilememiştir.");
    button.classList.remove("btn-active");
    button.classList.add("btn-passive");
    button.blur()

    //button.disabled = true;
    //button.classList.add("btn-disabled");
    //button.setAttribute("aria-disabled", "true");

    //// Set tooltip content (optional, since it's already in HTML)
    //tooltip.textContent = "Ekran okuyucu tarayıcınızda Türkçe dil desteği bulunmuyor.";
    //tooltip.hidden = false; // Ensure tooltip is not hidden (CSS handles visibility)

    //errorSpan.hidden = false;
    //errorSpan.textContent = "Ekran okuyucu tarayıcınızda Türkçe dil desteği bulunmuyor.";
}

// Sayfa yüklendiğinde Türkçe ses desteğini kontrol et
document.addEventListener("DOMContentLoaded", () => {
    waitForVoices(() => {
        //debugger;
        //if (!isTurkishVoiceAvailable()) {
        //    disableScreenReaderButton();
        //}
    });
});

document.addEventListener("keydown", function (event) {
    if (event.ctrlKey && event.key === "y") {
        event.preventDefault();
        toggleKeyPressMenu();
    }
});

function toggleMenu() {
    if (!menu) return;
    const isExpanded = menu.classList.toggle("show");
    menuButton.setAttribute("aria-expanded", isExpanded.toString());
}

function toggleKeyPressMenu() {
    toggleMenu();

    if (menu.classList.contains("show")) {
        document.addEventListener("keydown", handleMenuNavigation);
        const firstButton = menu.querySelector("button");
        if (firstButton) firstButton.focus();
    } else {
        document.removeEventListener("keydown", handleMenuNavigation);
    }
}

function handleMenuNavigation(event) {
    if (!menu || !menu.classList.contains("show")) return;

    const buttons = Array.from(menu.querySelectorAll("button"));
    const activeElement = document.activeElement;
    let index = buttons.indexOf(activeElement);

    if (event.key === "ArrowDown" || event.key === "ArrowRight") {
        event.preventDefault();
        if (index < buttons.length - 1) {
            buttons[index + 1].focus();
        } else {
            buttons[0].focus();
        }
    } else if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
        event.preventDefault();
        if (index > 0) {
            buttons[index - 1].focus();
        } else {
            buttons[buttons.length - 1].focus();
        }
    } else if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        if (activeElement.tagName === "BUTTON") {
            activeElement.click();
        }
    }
}

function enableScreenReader() {
    waitForVoices(() => {
        if (!isTurkishVoiceAvailable()) {
            disableScreenReaderButton();
            stopScreenReader();
            return;
        }

        isScreenReaderActive = !isScreenReaderActive;
        const button = document.getElementById("screenReaderToggleButton");

        if (isScreenReaderActive) {
            button.classList.remove("btn-passive");
            button.classList.add("btn-active");
            button.setAttribute("aria-pressed", "true");
            startScreenReader();
        } else {
            button.classList.remove("btn-active");
            button.classList.add("btn-passive");
            button.setAttribute("aria-pressed", "false");
            button.blur();
            stopScreenReader();
        }
    });
}

let synth = window.speechSynthesis;
let textQueue = [];

function startScreenReader() {
    textQueue = []; // Kuyruğu temizle

    // Tüm <h1>–<h6>, <p> ve başlık içindeki <a>’ları seç
    const contentElements = document.querySelectorAll("h1, h2, h3, h4, h5, h6, p");

    for (let i = 0; i < contentElements.length; i++) {
        const el = contentElements[i];

        if (!isVisible(el)) continue;

        const tagName = el.tagName.toLowerCase();
        const text = el.textContent.trim();
        if (!text) continue;

        if (tagName.startsWith("h")) {
            // Başlık varsa "Başlık:" etiketi ile ekle
            textQueue.push(`Başlık: ${text}`);
        } else if (tagName === "p") {
            // Paragraf varsa doğrudan ekle
            textQueue.push(text);
        }
    }

    readNext();
}

// Yardımcı: Eleman görünür mü?
function isVisible(el) {
    const style = window.getComputedStyle(el);
    const rect = el.getBoundingClientRect();

    return (
        style.display !== "none" &&
        style.visibility !== "hidden" &&
        rect.width > 0 &&
        rect.height > 0
    );
}





function stopScreenReader() {
    synth.cancel();
    textQueue = [];
}

function readNext() {
    if (textQueue.length === 0 || !isScreenReaderActive) return;

    const textToRead = textQueue.shift();
    const speech = new SpeechSynthesisUtterance(textToRead);
    const turkishVoice = synth.getVoices().find(voice => voice.lang === 'tr-TR');
    if (turkishVoice) {
        speech.voice = turkishVoice;
    }
    speech.lang = 'tr-TR';

    speech.onend = function () {
        readNext();
    };

    synth.speak(speech);
}

let isSelectedFieldReaderActive = false;

function enableSelectedFieldReader() {
    isSelectedFieldReaderActive = !isSelectedFieldReaderActive;
    const button = document.getElementById("selectedFieldReaderToggleButton");

    if (isSelectedFieldReaderActive) {
        button.classList.remove("btn-passive");
        button.classList.add("btn-active");
        button.setAttribute("aria-pressed", "true");
        enableFieldSelection();
    } else {
        button.classList.remove("btn-active");
        button.classList.add("btn-passive");
        button.setAttribute("aria-pressed", "false");
        button.blur();
        disableFieldSelection();
    }
}

function enableFieldSelection() {
    const selectableElements = document.querySelectorAll(".selectable");
    selectableElements.forEach((element) => {
        element.addEventListener("click", readSelectedField);
        element.classList.add("highlighted");
    });
}

function disableFieldSelection() {
    const selectableElements = document.querySelectorAll(".selectable");
    selectableElements.forEach((element) => {
        element.removeEventListener("click", readSelectedField);
        element.classList.remove("highlighted");
    });
}

function readSelectedField(event) {
    const textToRead = event.target.textContent.trim();
    const speech = new SpeechSynthesisUtterance(textToRead);
    const turkishVoice = synth.getVoices().find(voice => voice.lang === 'tr-TR');
    if (turkishVoice) {
        speech.voice = turkishVoice;
    }
    speech.lang = 'tr-TR';
    window.speechSynthesis.speak(speech);
}

function toggleFeature(feature, className, buttonId) {
    document.documentElement.classList.toggle(className);
    state[feature] = !state[feature];
    const button = document.getElementById(buttonId);

    if (state[feature]) {
        button.classList.remove("btn-passive");
        button.classList.add("btn-active");
        button.setAttribute("aria-pressed", "true");
    } else {
        button.classList.remove("btn-active");
        button.classList.add("btn-passive");
        button.setAttribute("aria-pressed", "false");
        button.blur();
    }
}

function addLineSpacing() {
    toggleFeature("lineHeight", "line-height", "lineHeightToggleButton");

    const isActive = document.documentElement.classList.contains('line-height');

    if (isActive) {
        // Açık durumda - !important ile override et
        document.querySelectorAll('.line-height *').forEach(el => {
            el.style.setProperty('line-height', '2', 'important');
        });
    } else {
        // Kapalı durumda - inline stilleri temizle
        document.querySelectorAll('*').forEach(el => {
            if (el.style.lineHeight) {
                el.style.removeProperty('line-height');
            }
        });
    }
}

function highlightLinks() {
    toggleFeature("highlightLinks", "highlight", "highlightLinksToggleButton");
}

function makeTextBigger() {
    toggleFeature("makeTextBigger", "bigger-text", "makeTextBiggerToggleButton");
}

function alignTextLeft() {
    toggleFeature("textAlignLeft", "align-text", "alighTextLeftToggleButton");
}

function makeCursorBigger() {
    toggleFeature(
        "makeCursorBigger",
        "bigger-cursor",
        "makeCursorBiggerToggleButton"
    );
}

function addReadingGuide() {
    clearReadingStates(
        "readingMask",
        "reading-mask-active",
        "readingMaskToggleButton"
    );
    toggleFeature(
        "readingGuide",
        "reading-guide-active",
        "readingGuideToggleButton"
    );
    if (state.readingGuide == true) {
        readingGuide.style.display = "block";
        document.addEventListener("mousemove", moveReadingGuide);
    } else {
        readingGuide.style.display = "none";
        document.removeEventListener("mousemove", moveReadingGuide);
    }
}

function moveReadingGuide(event) {
    readingGuide.style.top = `${event.clientY - 10}px`;
}

function addReadingMask() {
    clearReadingStates(
        "readingGuide",
        "reading-guide-active",
        "readingGuideToggleButton"
    );
    toggleFeature(
        "readingMask",
        "reading-mask-active",
        "readingMaskToggleButton"
    );

    if (state.readingMask == true) {
        readingMask.style.display = "block";
        document.addEventListener("mousemove", moveReadingMask);
    } else {
        readingMask.style.display = "none";
        document.removeEventListener("mousemove", moveReadingMask);
    }
}

function moveReadingMask(event) {
    const mouseY = event.clientY;
    const offset = 80;
    const topLine = document.querySelector(".reading-mask-line-top");
    topLine.style.top = `${mouseY - offset}px`;

    const bottomLine = document.querySelector(".reading-mask-line-bottom");
    bottomLine.style.top = `${mouseY + offset}px`;

    const topFade = document.querySelector(".fade-area-top");
    topFade.style.height = `${mouseY - offset}px`;

    const bottomFade = document.querySelector(".fade-area-bottom");
    bottomFade.style.height = `${window.innerHeight - mouseY - offset}px`;
}

function setDyslexicFriendlyFont() {
    toggleFeature(
        "setDyslexicFriendlyFont",
        "dyslexia-font",
        "setDyslexicFriendlyFontToggleButton"
    );
}

function addHighContrast() {
    toggleFeature(
        "toggleHighContrast",
        "high-contrast",
        "highContrastToggleButton"
    );
}

function desaturateColors() {
    clearSaturationStates("desaturate", "desaturateColors");
    toggleFeature(
        "desaturateColors",
        "desaturate",
        "desaturateColorsToggleButton"
    );
}

function reduceSaturation() {
    clearSaturationStates("low-saturation", "reduceSaturation");
    toggleFeature(
        "reduceSaturation",
        "low-saturation",
        "reduceSaturationToggleButton"
    );
}

function increaseSaturation() {
    clearSaturationStates("high-saturation", "increaseSaturation");
    toggleFeature(
        "increaseSaturation",
        "high-saturation",
        "increaseSaturationToggleButton"
    );
}

function removeImages() {
    toggleFeature("removeImages", "remove-images", "removeImagesToggleButton");
    
    const html = document.documentElement;
    const elements = document.querySelectorAll("*");

    if (html.classList.contains("remove-images")) {
        elements.forEach((el) => {
            const computedStyle = window.getComputedStyle(el);
            const bgImage = computedStyle.getPropertyValue("background-image");
            const bg = computedStyle.getPropertyValue("background");

            if (bgImage && bgImage.includes("url")) {
                if (!el.hasAttribute("data-bg-image")) {
                    el.setAttribute("data-bg-image", bgImage);
                }
                el.style.setProperty("background-image", "none", "important");
            }

            if ((!bgImage || bgImage === "none") && bg.includes("url")) {
                if (!el.hasAttribute("data-bg")) {
                    el.setAttribute("data-bg", bg);
                }
                el.style.setProperty("background", "none", "important");
            }
        });

        document.querySelectorAll("img").forEach((img) => {

            if (!img.hasAttribute("data-original-visibility")) {
                const visibility = window
                    .getComputedStyle(img)
                    .getPropertyValue("visibility");
                img.setAttribute("data-original-visibility", visibility);
            }

            img.style.setProperty("visibility", "hidden", "important");
        });
    } else {
        elements.forEach((el) => {
            if (el.hasAttribute("data-bg-image")) {
                const original = el.getAttribute("data-bg-image");
                el.style.setProperty("background-image", original, "important");
                el.removeAttribute("data-bg-image");
            }

            if (el.hasAttribute("data-bg")) {
                const original = el.getAttribute("data-bg");
                el.style.setProperty("background", original, "important");
                el.removeAttribute("data-bg");
            }
        });

        document.querySelectorAll("img").forEach((img) => {
            if (img.hasAttribute("data-original-visibility")) {
                const original = img.getAttribute("data-original-visibility");
                img.style.setProperty("visibility", original, "important");
                img.removeAttribute("data-original-visibility");
            }
        });

    }
}

function clearSaturationStates(className, feature) {
    if (document.documentElement.classList.contains(className)) {
        return;
    }

    const saturationClasses = ["desaturate", "high-saturation", "low-saturation"];
    const buttons = {
        desaturate: "desaturateColorsToggleButton",
        "high-saturation": "increaseSaturationToggleButton",
        "low-saturation": "reduceSaturationToggleButton",
    };

    saturationClasses.forEach((saturationClass) => {
        if (document.documentElement.classList.contains(saturationClass)) {
            document.documentElement.classList.remove(saturationClass);
            state[feature] = false;

            const button = document.getElementById(buttons[saturationClass]);
            if (button) {
                button.classList.remove("btn-active");
                button.classList.add("btn-passive");
                button.setAttribute("aria-pressed", "false");
                button.blur();
            }
        }
    });
}

function clearReadingStates(feature, className, buttonId) {
    if (!document.getElementById(buttonId).classList.contains("btn-active"))
        return;

    state[feature] = false;
    document.documentElement.classList.remove(className);

    const button = document.getElementById(buttonId);
    button.classList.remove("btn-active");
    button.classList.add("btn-passive");
    button.setAttribute("aria-pressed", "false");
    button.blur();

    if (feature == "readingGuide") {
        readingGuide.style.display = "none";
        document.removeEventListener("mousemove", moveReadingGuide);
    } else {
        readingMask.style.display = "none";
        document.removeEventListener("mousemove", moveReadingMask);
    }
}

function clearAllStates() {
    document.documentElement.className = "";
    state = {};

    const buttons = document.querySelectorAll(".acc-menu button");
    buttons.forEach((b) => {
        b.classList.remove("btn-active");
        b.classList.add("btn-passive");
        b.setAttribute("aria-pressed", "false");
        b.blur();
    });

    readingGuide.style.display = "none";
    document.removeEventListener("mousemove", moveReadingGuide);

    readingMask.style.display = "none";
    document.removeEventListener("mousemove", moveReadingMask);

    const elements = document.querySelectorAll("*");
    elements.forEach((el) => {
        if (el.hasAttribute("data-bg-image")) {
            const original = el.getAttribute("data-bg-image");
            el.style.setProperty("background-image", original, "important");
            el.removeAttribute("data-bg-image");
        }

        if (el.hasAttribute("data-bg")) {
            const original = el.getAttribute("data-bg");
            el.style.setProperty("background", original, "important");
            el.removeAttribute("data-bg");
        }
    });

    document.querySelectorAll("img").forEach((img) => {
        if (img.hasAttribute("data-original-visibility")) {
            const original = img.getAttribute("data-original-visibility");
            img.style.setProperty("visibility", original, "important");
            img.removeAttribute("data-original-visibility");
        }
    });


    document.querySelectorAll('*').forEach(el => {
        if (el.style.lineHeight) {
            el.style.removeProperty('line-height');
        }
    });
};
