// eu espero nunca mais precisar usar esse inferno de linguagem na vida.
// ja fiz isso tudo no chatgpt, eu odeio javascript.
// terminado isso, alô a quem tá patrulhando <3, e eu espero que isso não dê erro e eu precise abrir o common.js dnv
function getEdits() {
	let edits;
	let todayEdits;
	let weekEdits;
	let monthEdits;
	
	const menuList = document.querySelector('.vector-menu-content-list');
	
	function fetchEdits(date) {
	    const apiUrl = `https://xtools.wmcloud.org/api/user/simple_editcount/pt.wikipedia.org/Eduardo Gottert/all/${date}/${date}`;
	
	    return fetch(apiUrl)
	        .then(response => {
	            if (!response.ok) {
	                throw new Error('Network response was not ok ' + response.statusText);
	            }
	            return response.json();
	        })
	        .then(data => {
	            return data.live_edit_count + data.deleted_edit_count; // Return the total edit count
	        })
	        .catch(error => {
	            console.error('There was a problem with the fetch operation:', error);
	        });
	}
	
	function fetchWeeklyEdits(startDate, endDate) {
	    const apiUrl = `https://xtools.wmcloud.org/api/user/simple_editcount/pt.wikipedia.org/Eduardo Gottert/all/${startDate}/${endDate}`;
	
	    return fetch(apiUrl)
	        .then(response => {
	            if (!response.ok) {
	                throw new Error('Network response was not ok ' + response.statusText);
	            }
	            return response.json();
	        })
	        .then(data => {
	            return data.live_edit_count + data.deleted_edit_count; // Return the total weekly edit count
	        })
	        .catch(error => {
	            console.error('There was a problem with the fetch operation:', error);
	        });
	}
	
	function fetchMonthlyEdits(startDate, endDate) {
	    const apiUrl = `https://xtools.wmcloud.org/api/user/simple_editcount/pt.wikipedia.org/Eduardo Gottert/all/${startDate}/${endDate}`;
	
	    return fetch(apiUrl)
	        .then(response => {
	            if (!response.ok) {
	                throw new Error('Network response was not ok ' + response.statusText);
	            }
	            return response.json();
	        })
	        .then(data => {
	            return data.live_edit_count + data.deleted_edit_count; // Return the total monthly edit count
	        })
	        .catch(error => {
	            console.error('There was a problem with the fetch operation:', error);
	        });
	}
	
	function getToday() {
	    const today = new Date();
	    const year = today.getFullYear();
	    const month = String(today.getMonth() + 1).padStart(2, '0');
	    const day = String(today.getDate()).padStart(2, '0');
	
	    return `${year}-${month}-${day}`;
	}
	
	function getWeekStartDate() {
	    const today = new Date();
	    today.setDate(today.getDate() - 6);
	
	    const year = today.getFullYear();
	    const month = String(today.getMonth() + 1).padStart(2, '0');
	    const day = String(today.getDate()).padStart(2, '0');
	
	    return `${year}-${month}-${day}`; // Format as yyyy-mm-dd
	}
	
	function getLast30DaysStartDate() {
	    const today = new Date();
	    today.setDate(today.getDate() - 30); // Set to 30 days ago
	
	    const year = today.getFullYear();
	    const month = String(today.getMonth() + 1).padStart(2, '0');
	    const day = String(today.getDate()).padStart(2, '0');
	
	    return `${year}-${month}-${day}`; // Format as yyyy-mm-dd
	}
	
	if (menuList && menuList.firstChild) {
	    const newMenuItem = document.createElement('li');
	    const newLink = document.createElement('a');
	    const dropdown = document.createElement('div');
	
	    // Set up dropdown menu
	    dropdown.classList.add('dropdown');
	    dropdown.style.display = 'none'; // Initially hidden
		dropdown.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.1)';
	
	    fetch('https://xtools.wmcloud.org/api/user/simple_editcount/pt.wikipedia.org/Eduardo Gottert/all/2000-01-01/2035-01-31')
	    .then(response => {
	        if (!response.ok) {
	            throw new Error('Network response was not ok');
	        }
	        return response.json(); // Parse the JSON from the response
	    })
	    .then(data => {
	        edits = data.live_edit_count + data.deleted_edit_count;
	
	        // Fetch today's edits
	        const todayPromise = fetchEdits(getToday());
	        // Fetch weekly edits
	        const weekPromise = fetchWeeklyEdits(getWeekStartDate(), getToday());
	        // Fetch monthly edits
	        const monthPromise = fetchMonthlyEdits(getLast30DaysStartDate(), getToday());
	
	        return Promise.all();
	    })
	    .then(results => {
	        todayEdits = results;
	        weekEdits = results;
	        monthEdits = results;
	
	        const newText = `Edits: ${edits} (${todayEdits})`;
	        newLink.textContent = newText;
	        newLink.href = "https://pt.wikipedia.org/w/index.php?title=Especial:Contribuições/Eduardo Gottert&target=Eduardo Gottert&offset=&limit=100";
			
			
			const dailyDate = getToday();
			const weeklyDate = getWeekStartDate();
			const monthlyDate = getLast30DaysStartDate();
			
			const dailyUrl = `https://pt.wikipedia.org/w/index.php?title=Especial%3AContribuições&target=Eduardo Gottert&namespace=all&tagfilter=&start=${dailyDate}&end=${getToday()}&limit=100`;
			const weeklyUrl = `https://pt.wikipedia.org/w/index.php?title=Especial%3AContribuições&target=Eduardo Gottert&namespace=all&tagfilter=&start=${weeklyDate}&end=${getToday()}&limit=100`;
			const monthlyUrl = `https://pt.wikipedia.org/w/index.php?title=Especial%3AContribuições&target=Eduardo Gottert&namespace=all&tagfilter=&start=${monthlyDate}&end=${getToday()}&limit=100`;
			const totalUrl = `https://pt.wikipedia.org/w/index.php?title=Especial:Contribuições/Eduardo Gottert&target=Eduardo Gottert&offset=&limit=100`;
			
	        // Create dropdown content
	        dropdown.innerHTML = `
	        	<a href="${dailyUrl}">Daily Edits: ${todayEdits}</a>
	            <a href="${weeklyUrl}">Weekly Edits: ${weekEdits}</a>
	            <a href="${monthlyUrl}">Monthly Edits: ${monthEdits}</a>
				<a href="${totalUrl}">Total Edits: ${edits}</a>
	        `;
	        
	        // Append link and dropdown to the menu item
	        newMenuItem.appendChild(newLink);
	        newMenuItem.appendChild(dropdown);
	        
	        const itemToRemove = document.getElementById('pt-mycontris');
	        if (itemToRemove) {
	            itemToRemove.remove(); // Remove the item from the DOM
	        }
	        
	        menuList.insertBefore(newMenuItem, menuList.children);
	
	        // Show dropdown on hover
	        newMenuItem.addEventListener('mouseenter', () => {
	            dropdown.style.display = 'block'; // Show dropdown
	        });
	        newMenuItem.addEventListener('mouseleave', () => {
	            dropdown.style.display = 'none'; // Hide dropdown
	        });
			
	
			// Seleciona o <span> dentro do <a> que está dentro do <li> com id "pt-userpage"
			const spanElement = document.querySelector('#pt-userpage a span');
	
			// Verifica se o spanElement existe antes de tentar alterar seu conteúdo
			if (spanElement) {
				spanElement.innerHTML = `
					<span style="color:#4444F2;font-family:Palatino Linotype">
						<b><u>Eduardo <span style="color:#000000">G.</span></u></b>
				`;
			}
	    })
	    .catch(error => {
	        console.error('There was a problem with the fetch operation:', error);
	    });
	}
}

function setUserDropdownMenu() {
	const dropdown = document.createElement('div');
	const user = document.getElementById('pt-userpage');
	
	dropdown.classList.add('dropdown');
    dropdown.style.display = 'none';
	dropdown.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.1)';
    
    dropdown.innerHTML = `
	        	<a href="https://pt.wikipedia.orghttps://wikines.com/pt/Usuário Discussão:Eduardo Gottert">Discussão</a>
	            <a href="https://pt.wikipedia.org/w/index.php?title=Especial:Contribuições/Eduardo Gottert&target=Eduardo Gottert&offset=&limit=100">Contribuições</a>
	            <a href="https://pt.wikipedia.orghttps://wikines.com/pt/Usuário:Eduardo_Gottert/TODO">Por Fazer</a>
	            <a href="https://xtools.wmcloud.org/ec/pt.wikipedia.org/Eduardo Gottert">XTools Edits</a>
	            <a href="https://pt.wikipedia.orghttps://wikines.com/pt/Usuário:Eduardo Gottert/Testes">Pág. Testes</a>
	            <a href="https://pt.wikipedia.orghttps://wikines.com/pt/Especial:P%C3%A1ginas_vigiadas?hidepreviousrevisions=1&hidecategorization=1&hideWikibase=1&limit=50&days=30&enhanced=1&urlversion=2">Watchlist</a>`;

    user.appendChild(dropdown);
    
    user.addEventListener('mouseenter', () => {
        dropdown.style.display = 'block'; // Show dropdown
    });
    user.addEventListener('mouseleave', () => {
        dropdown.style.display = 'none'; // Hide dropdown
    });
}

function removeTestsFromNavbar() {
	const itemToRemove = document.getElementById('pt-sandbox');
    if (itemToRemove) {
        itemToRemove.remove(); // Remove the item from the DOM
    }
}

function beautifyNavbar() {
	const itemsToRemove = ;
	
	for (let item of itemsToRemove) {
		const _item = document.getElementById(item);
		if (_item) {
			_item.remove();
		}
	}
	
	const menuList = document.querySelector('.vector-menu-content-list');
	
	// Create an image element as the menu icon
	const img = document.createElement('img');
    img.src = 'https://cdn-icons-png.flaticon.com/512/2893/2893421.png';
    img.alt = 'Configurações';
    img.width = 24;
    img.height = 24;
    img.style.cursor = 'pointer';
    img.style.paddingBottom = '6px';
	
	// Create a new list item to hold the dropdown menu
	const newMenuItem = document.createElement('li');
	newMenuItem.style.position = 'relative'; // Ensure dropdown is positioned relative to this element
	
	// Create the dropdown container
	const dropdown = document.createElement('div');
	dropdown.classList.add('dropdown');
    dropdown.style.display = 'none'; // Initially hidden
	dropdown.style.top = '32px'; // Position below the icon (24px height + some padding)
	dropdown.style.right = '0'; // Align dropdown to the right edge of newMenuItem to open leftwards
	dropdown.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.1)';
	
	dropdown.innerHTML = `
		<ul style="list-style-type: none; margin: 0; padding: 0; font-size: 16px; background-color: #f9f9f9; text-align: center">
		<li id="pt-preferences"><a href="https://pt.wikipedia.orghttps://wikines.com/pt/Especial:Preferências">Preferências</a></li>
		<li id="pt-betafeatures"><a href="https://pt.wikipedia.orghttps://wikines.com/pt/Especial:Preferências#mw-prefsection-betafeatures">Beta</a></li>
		<li> ⠀ ⠀ ⠀ ⠀ ⠀</li>
		<li id="pt-logout"><a href="https://pt.wikipedia.org/w/index.php?title=Especial:Sair&amp;returnto=Usu%C3%A1rio%3AEduardo Gottert%2Fcommon.js&amp;returntoquery=action%3Dedit">Sair</a></li></ul>`;
    
	// Append the dropdown and image to the new menu item
	newMenuItem.appendChild(img);
	newMenuItem.appendChild(dropdown);
	
	// Toggle dropdown visibility on click
	img.addEventListener('mouseenter', function(event) {
		event.stopPropagation(); // Prevent click from affecting other elements
		dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
	});
	
	// Hide dropdown when mouse leaves the img or dropdown
	const handleMouseLeave = function() {
		dropdown.style.display = 'none';
	};

	newMenuItem.addEventListener('mouseleave', handleMouseLeave);
	dropdown.addEventListener('mouseleave', handleMouseLeave);

	// Append the new menu item to the menu list
	menuList.appendChild(newMenuItem);
}

function openModal() {
    const modalHtml = `
     <div id="incidentModal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.2); display: flex; justify-content: center; align-items: center; z-index: 1000;">
        <div style="background-color: white; padding: 10px; border: 1px solid #a2a9b1; border-radius: 3px; width: 600px; max-width: 90%; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1); background:#fefefe; margin-right:10px;">
            <h3 style="margin-top: 0; font-size: 16px; font-weight: normal; color: #222222; border:1px solid gray; border-radius:10px; text-align:center; background:#d8d8d8">Notificar Incidente</h3>
            <label for="name" style="font-size: 14px; color: #555; display: block; margin-bottom: 5px;">Nome:</label>
            <input type="text" id="name" placeholder="Nome" style="width: 100%; margin-bottom: 10px; padding: 5px; font-size: 14px; border: 1px solid #a2a9b1; border-radius: 3px;">
            <label for="reason" style="font-size: 14px; color: #555; display: block; margin-bottom: 5px;">Razão:</label>
            <textarea id="reason" placeholder="Razão" style="width: 100%; margin-bottom: 10px; padding: 5px; font-size: 14px; border: 1px solid #a2a9b1; border-radius: 3px; height: 240px;"></textarea>
            <label for="vandal" style="font-size: 14px; color: #555; display: block; margin-bottom: 5px; float:left">Vandalismo: </label>
            <input type="checkbox" id="vandal" style="margin-bottom: 10px; padding: 5px; font-size: 16px; border: 1px solid #a2a9b1; border-radius: 3px; text-align:center">
            <div style="text-align: right; margin-top: 15px;">
                <button onclick="submitIncident()" style="background-color: #f0f0f0; color: #222; border: 1px solid #a2a9b1; padding: 5px 10px; border-radius: 3px; cursor: pointer; font-size: 14px; margin-right: 5px;">Enviar</button>
                <button onclick="closeModal()" style="background-color: #f0f0f0; color: #222; border: 1px solid #a2a9b1; padding: 5px 10px; border-radius: 3px; cursor: pointer; font-size: 14px;">Fechar</button>
            </div>
        </div>
    </div>
    <style>
        /* Fixing the focus border color for input */
        #incidentModal input:focus, #incidentModal textarea:focus {
            border-color: #005a9c;
            outline: none;
        }

        /* Adding padding and box-sizing to avoid inputs touching the edges */
        #incidentModal input, #incidentModal textarea {
            box-sizing: border-box; /* Ensures padding is included in the width calculation */
        }

        /* Hover effect for buttons */
        #incidentModal button:hover {
            background-color: #e5e5e5;
        }
    </style>
`;
    document.body.insertAdjacentHTML('beforeend', modalHtml);
}

// Function to submit the incident and open the link
function submitIncident() {
    const name = document.getElementById('name').value;
    const reason = document.getElementById('reason').value;
	const checkbox = document.getElementById('vandal');
	const type = checkbox.checked ? "NV" : "NI";
	let url = '';
	
    if (name && reason) {
    	if (type == "NV") {
            url = `https://pt.wikipedia.org/w/index.php?title=Wikipédia:Pedidos/Notificações_de_vandalismo&action=edit&section=new&preload=Usuário:Eduardo_Gottert/NI&preloadparams%5b%5d=${encodeURIComponent(name)}&preloadparams%5b%5d=${encodeURIComponent(reason)}&preloadparams%5b%5d=%7e%7e%7e%7e`;
    	} else {
    		url = `https://pt.wikipedia.org/w/index.php?title=Wikipédia:Pedidos/Notificação_de_incidentes&action=edit&section=new&preload=Usuário:Eduardo_Gottert/NI&preloadparams%5b%5d=${encodeURIComponent(name)}&preloadparams%5b%5d=${encodeURIComponent(reason)}&preloadparams%5b%5d=%7e%7e%7e%7e`;
    	}
        window.open(url, '_blank'); // Open the URL in a new tab
        closeModal(); // Close the modal
    } else {
        alert("Por favor, preencha todos os campos.");
    }
}

// Function to close the modal
function closeModal() {
    const modal = document.getElementById('incidentModal');
    if (modal) {
        modal.remove();
    }
}

// Function to create the button and dropdown
function createCommunityButton() {
    const menuList = document.querySelector('.vector-menu-content-list');

    // Create an image element as the menu icon
    const img = document.createElement('img');
    img.src = 'https://www.freeiconspng.com/thumbs/community-icon/community-icon-6.png';
    img.alt = 'Comunidade & Votações';
    img.width = 24;
    img.height = 24;
    img.style.cursor = 'pointer';
    img.style.paddingBottom = '6px';

    // Create a new list item to hold the dropdown menu
    const newMenuItem = document.createElement('li');
    newMenuItem.style.position = 'relative'; // Ensure dropdown is positioned relative to this element

    // Create the dropdown container
    const dropdown = document.createElement('div');
    dropdown.classList.add('dropdown');
    dropdown.style.display = 'none'; // Initially hidden
    dropdown.style.top = '32px'; // Position below the icon (24px height + some padding)
    dropdown.style.right = '0'; // Align dropdown to the right edge of newMenuItem to open leftwards
    dropdown.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.1)';
    dropdown.style.width = '150px';

    dropdown.innerHTML = `
        <ul style="list-style-type: none; margin: 0; padding: 0; font-size: 16px; background-color: #f9f9f9; text-align: center">
        <li>
        	<a href="https://pt.wikipedia.orghttps://wikines.com/pt/Wikipédia:Esplanada" alt="Clique para acessar WP:E">Esplanada</a>
        	<a style="font-size:11px" href="https://pt.wikipedia.orghttps://wikines.com/pt/Wikipédia:Esplanada/geral" alt="Clique para acessar WP:E/geral">(ger)</a>
        	<a style="font-size:11px" href="https://pt.wikipedia.orghttps://wikines.com/pt/Wikipédia:Esplanada/propostas" alt="Clique para acessar WP:E/propostas">(prop)</a>
        <li></li>
        <li><a href="https://pt.wikipedia.orghttps://wikines.com/pt/Categoria:!Itens_propostos_para_eliminação" alt="Clique aqui">Propostas de Eliminação</a></li>
        <li><a href="https://pt.wikipedia.orghttps://wikines.com/pt/Especial:Categorias_de_rastreamento" alt="Clique aqui">Cat. Rastreamento</a></li>
        <li><a href="https://pt.wikipedia.orghttps://wikines.com/pt/Wikipédia:Pedidos_a_administradores/Discussão_de_bloqueio" alt="Clque para acessar as DBL">Disc. Bloqueios</a></li>
        <li>
            <a href="https://pt.wikipedia.orghttps://wikines.com/pt/Wikipédia:Pedidos/Notificação_de_incidentes" alt="Clique aqui">Notif. Incidentes</a>
            <span>/</span>
            <a href="https://pt.wikipedia.orghttps://wikines.com/pt/Wikipédia:Pedidos/Notificações_de_vandalismo" alt="Clique aqui">NV</a>
            <a href="#" onclick="openModal()" alt="Clique para adicionar um incidente">(+)</a>
        </li>
        <li><a href="https://pt.wikipedia.orghttps://wikines.com/pt/Ajuda:Tire_suas_dúvidas" alt="Clique aqui">Tire suas Dúvidas</a></li>
        <li><a href="https://pt.wikipedia.org/w/index.php?title=Especial:Registro_de_abusos" alt="Clique aqui">Registros do Filtro</a></li>
        <li>
			<a href="https://pt.wikipedia.orghttps://wikines.com/pt/WP:CS">Adm</a>
			<a href="https://pt.wikipedia.orghttps://wikines.com/pt/WP:CE">Elim</a>
			<a href="https://pt.wikipedia.orghttps://wikines.com/pt/WP:CP">Prog</a>
        </li>
        <li>
        	<a href="https://pt.wikipedia.orghttps://wikines.com/pt/WP:CC">Cat</a>
			<a href="https://pt.wikipedia.orghttps://wikines.com/pt/WP:CT">Trad</a>
			<a href="https://pt.wikipedia.orghttps://wikines.com/pt/WP:CB">Buro</a>
        </li>
        </ul>`;

    // Append the dropdown and image to the new menu item
    newMenuItem.appendChild(img);
    newMenuItem.appendChild(dropdown);

    // Toggle dropdown visibility on click
    img.addEventListener('mouseenter', function(event) {
        event.stopPropagation(); // Prevent click from affecting other elements
        dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
    });

    // Hide dropdown when mouse leaves the img or dropdown
    const handleMouseLeave = function() {
        dropdown.style.display = 'none';
    };

    newMenuItem.addEventListener('mouseleave', handleMouseLeave);
    dropdown.addEventListener('mouseleave', handleMouseLeave);

    // Insert the new menu item as the penultimate item
    const lastMenuItem = menuList.lastElementChild;
    menuList.insertBefore(newMenuItem, lastMenuItem);
}
getEdits();
setUserDropdownMenu();
removeTestsFromNavbar();
beautifyNavbar();
createCommunityButton();

const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        // Check for added nodes
        mutation.addedNodes.forEach((node) => {
            if (node.id === 'pt-darkmode') {
                // If the dark mode button is added, remove it
                node.remove();
            }
        });
    });
});

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