const chatWindow = document.getElementById('chatWindow');
    const userInput = document.getElementById('userInput');
    const sendBtn = document.getElementById('sendBtn');
    // Funzione per aggiungere un messaggio alla finestra della chat
    function addMessage(message, sender) {
        const messageElement = document.createElement('div');
        messageElement.classList.add('message', sender);
        if (sender === 'bot') {
            const userIcon = document.createElement('div');
            userIcon.classList.add('userIcon');
            userIcon.innerHTML = '
'; // Cambia il percorso dell'icona
            messageElement.appendChild(userIcon);
            setItemWithExpiry('sessioneAttiva', true, 3600000);
        }
        const textElement = document.createElement('span');
        textElement.textContent = message;
        messageElement.appendChild(textElement);
        chatWindow.appendChild(messageElement);
        chatWindow.scrollTop = chatWindow.scrollHeight;
    }
	function setItemWithExpiry(key, value, ttl) {
		const now = new Date();
		const item = {
			value: value,
			expiry: now.getTime() + ttl,
		};
		localStorage.setItem(key, JSON.stringify(item));
	}
	function getItemWithExpiry(key) {
		const itemStr = localStorage.getItem(key);
		if (!itemStr) {
			return null;
		}
		const item = JSON.parse(itemStr);
		const now = new Date();
		if (now.getTime() > item.expiry) {
			localStorage.removeItem(key);
			return null;
		}
		return item.value;
	}
	function showWelcomeMessage() {
		const domandeProposte = [
			//'Domanda?'
		];
		const domandeProposteId = [
		];
		// Funzione per mescolare l'array
		function shuffleArray(array) {
		  for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			[array[i], array[j]] = [array[j], array[i]];
		  }
		  return array;
		}
		// Mescola l'array e prendi le prime 3 domande
		const domandeRandom = shuffleArray(domandeProposte).slice(0, 2);
		const sessioneAttiva = getItemWithExpiry('sessioneAttiva');
					if (sessioneAttiva == null) {
				// Aggiungi un messaggio vuoto per il bot
				addMessage('', 'bot');
				const lastMessage = chatWindow.lastChild.querySelector('span');
				// const welcomeText = 'Ciao, sono il tuo assistente personale, sono pronto ad aiutarti. You can ask me in your language, je parle plusieurs langues. Altri utenti mi hanno chiesto: ' + domandeRandom.join(' ');
				const welcomeText = 'Ciao, sono Camilla il tuo assistente personale Cresceresani. I miei creatori hanno compiuto ogni ragionevole sforzo per assicurare che i dati che fornisco siano accurati ed in accordo con gli standard accettati al momento della sua realizzazione. Non intendo fornire consigli sullo stato di salute (o di deviazione dalla normalità) di un singolo bambino/a, non posso essere impiegata in alcun modo per la diagnosi di un problema di crescita, né sostituirsi in alcun modo al parere professionale di un medico. Per ogni problema specifico relativo al singolo bambino/a si raccomanda sempre di consultare uno specialista. L’utilizzo di qualsiasi informazione ottenibile dalle miei risposte è a discrezione dell’utilizzatore. Gli Autori declinano qualsiasi responsabilità, espressa o implicita, rispetto ad eventuali errori di utilizzo';
				// Applica l'effetto typing
				showTypingEffect(welcomeText, lastMessage);
				// Salva la sessione attiva
				// 3600000 1 ora
				setItemWithExpiry('sessioneAttiva', true, 3600000);
			}
			else
			{
				// Recupera ultima domanda e risposta
				// Recupera ultima domanda e risposta
				const ultima = localStorage.getItem('anthecb_ultimaInterazione');
				if (ultima) {
				    const data = JSON.parse(ultima);
				    if (Array.isArray(data)) {
					data.forEach(item => {
					    if (item.domanda) addMessage(item.domanda, 'user');
					    if (item.risposta) {
					    	item.risposta = parseMarkdownLinks(item.risposta);
						addMessage('', 'bot');
						const lastMsg = chatWindow.lastChild.querySelector('span');
						lastMsg.innerHTML = item.risposta;
					    }
					});
				    }
					// Aggiungi il messaggio di benvenuto in coda
					const welcomeText = 'Ciao di nuovo, mi fa piacere rivederti. Come posso aiutarti? Ricorda di leggere il nostro disclaimer';
					addMessage('', 'bot');
					const lastWelcome = chatWindow.lastChild.querySelector('span');
					lastWelcome.innerHTML = welcomeText;
				} else {
					// Aggiungi un messaggio vuoto per il bot
					addMessage('', 'bot');
					const lastMessage = chatWindow.lastChild.querySelector('span');
					//const welcomeText = 'Ciao di nuovo, mi fa piacere rivederti. Come posso aiutarti? Recentemente mi hanno chiesto: ' + domandeRandom.join(' ');
					const welcomeText = 'Ciao di nuovo, mi fa piacere rivederti. Come posso aiutarti? Ricorda di leggere il nostro disclaimer';
					// Applica l'effetto typing
					showTypingEffect(welcomeText, lastMessage);
				}
			}
			}
	function sendMessageFromLink(question) {
		userInput.value = question;
		sendMessage();
	}
    // Funzione per l'effetto di typing
	function showTypingEffect(html, element) {
		html = parseMarkdownLinks(html);
		let index = 0;
		const interval = setInterval(() => {
			if (index < html.length) {
				element.innerHTML = html.substring(0, index + 1); // Usa innerHTML per aggiornare gradualmente il contenuto
				index++;
				chatWindow.scrollTop = chatWindow.scrollHeight;
			} else {
				clearInterval(interval);
			}
		}, 15);
	}
	function linkify(text) {
		return text.replace(
			/(https?:\/\/[^\s]+)/g,
			'$1'
		);
	}
	function formatBotResponse(text) {
		let html = parseMarkdownLinks(text);
		html = linkify(html);
		return html;
	}
	function parseMarkdownLinks(text) {
		// Converte [testo](url) in testo
		return text.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
			'$1');
	}
    // Funzione per inviare un messaggio
    function sendMessage() {
        const message = userInput.value;
        if (message.trim() !== "") {
            addMessage(message, 'user');
            userInput.value = "";
            // Mostra un indicatore di typing
            const botMessageElement = document.createElement('div');
            botMessageElement.classList.add('message', 'bot');
            botMessageElement.innerHTML = '