// content.js

// Log that the content script is running
console.log("Content script is running.");


let fontLoaded = false;

function loadFont() {
    const fontUrl = chrome.runtime.getURL("fonts/fot_rodin_pro_m.ttf");
    const style = document.createElement('style');
    style.textContent = `
        @font-face {
            font-family: 'Wii NTLG PGothic JPN Regular';
            src: url('${fontUrl}') format('truetype');
        }
        body {
            font-family: 'Wii NTLG PGothic JPN Regular', sans-serif !important;
        }
        * {
            font-family: 'Wii NTLG PGothic JPN Regular', sans-serif !important;
        }
        #text03-01 {
            display: flex; /* Enable flexbox */
            justify-content: center; /* Center horizontally */
            align-items: center; /* Center vertically */
            height: 100vh; /* Full height of the viewport */
            width: 100%; /* Full width */
        }

        #text05-01 {
            display: flex; /* Enable flexbox */
            justify-content: center; /* Center horizontally */
            align-items: center; /* Center vertically */
            height: 100vh; /* Full height of the viewport */
            width: 100%; /* Full width */
        }
        
        #text06-01 {
            display: flex; /* Enable flexbox */
            justify-content: center; /* Center horizontally */
            align-items: center; /* Center vertically */
            height: 100vh; /* Full height of the viewport */
            width: 100%; /* Full width */
        }

        .buttonTextBlackM {
            font-size: 24px; /* Adjust font size as needed */
            color: black; /* Set text color */
            text-align: center; /* Center text within the div */
        }
    `;

    // Try to append to the head first
    const head = document.head || document.getElementsByTagName('head')[0];
    if (head) {
        head.appendChild(style);
        console.log("Font loaded into <head>.");
        return "Font loaded into <head>"; // Return success message
    }

    // If head is not available, use MutationObserver to wait for it
    const observer = new MutationObserver(() => {
        const head = document.head || document.getElementsByTagName('head')[0];
        if (head) {
            head.appendChild(style);
            observer.disconnect(); // Stop observing once the style is added
            console.log("Font loaded into <head> via MutationObserver.");
            return "Font loaded into <head> via MutationObserver"; // Return success message
        }
    });

    // Start observing the document for changes
    observer.observe(document, { childList: true, subtree: true });

    // Fallback: If the head is still not available, append to the body
    const fallbackTimeout = setTimeout(() => {
        if (!document.head || !document.head.contains(style)) {
            document.body.appendChild(style);
            console.log("Font loaded into <body> as a fallback.");
            observer.disconnect(); // Stop observing if we fall back
            return "Font loaded into <body> as a fallback"; // Return success message
        }
    }, 1000); // Wait for 1 second before falling back

    // Check if the observer is still active after 2 seconds
    setTimeout(() => {
        // If the font is still not loaded, log an error
        if (!document.head || !document.body.contains(style)) {
            console.error("Failed to load font: <head> and <body> are not available.");
            return "Failed to load font: <head> and <body> are not available."; // Return error message
        }
        observer.disconnect(); // Clear the observer
        clearTimeout(fallbackTimeout); // Clear the timeout
    }, 2000); // Check again after 2 seconds

    return "Font loading initiated"; // Return initial status
}

// Check the font state on page load

function checkFontState() {
    chrome.storage.local.get(['fontDisabled'], function(result) {
        if (!result.fontDisabled) {
            return loadFont();  
        } else {
            return "disabled";
        }
    });
}

const soundFilePaths = [
  '', // Index 0 (unused)
  'audio/1.wav',
  'audio/2.wav',
  'audio/3.wav',
  'audio/4.wav',
  'audio/5.wav',
  'audio/6.wav',
  'audio/7.wav'
];

// Generate the full, web-accessible URLs
const generatedSoundUrls = [];
for (let i = 0; i < soundFilePaths.length; i++) {
  if (soundFilePaths[i]) {
    // Use browser.runtime.getURL for Firefox
    generatedSoundUrls[i] = browser.runtime.getURL(soundFilePaths[i]);
  } else {
    generatedSoundUrls[i] = '';
  }
}

// Function to load class definitions based on the browser
const loadClassDefinitions = async () => {
    let classDefinitionsUrl;
    const userAgent = navigator.userAgent.toLowerCase();

    if (userAgent.includes("chrome")) {
        classDefinitionsUrl = chrome.runtime.getURL('classDefinitions.js');
    } else if (userAgent.includes("firefox")) {
        classDefinitionsUrl = browser.runtime.getURL('classDefinitions.js');
    } else {
        console.warn("Unsupported browser. Class definitions will not be loaded.");
        return;
    }

    try {
        const response = await fetch(classDefinitionsUrl);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const classDefinitionsText = await response.text();

        const script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');

        // PREPEND the sound URLs as a global variable *before* the classDefinitions.js content
        script.textContent = `
            (function() {
                // Define a global variable that classDefinitions.js can access
                window._wiiShopSoundUrls_ = ${JSON.stringify(generatedSoundUrls)};
            })();
        ` + classDefinitionsText; // Append the actual classDefinitions.js content

        document.documentElement.insertBefore(script, document.documentElement.firstChild);

        script.onload = function() {
            this.remove();
            // Clean up the global variable after classDefinitions.js has likely used it
            delete window._wiiShopSoundUrls_;
        };

    } catch (error) {
        console.error("Failed to load class definitions:", error);
    }
};

// Load the class definitions
loadClassDefinitions();
// Load the existing trace and points from localStorage
const result = checkFontState();
console.log(result);