import { ALL_EMOJIS } from './emoji.js';
import { checkWithOllama } from './ollama.js';

document.addEventListener("DOMContentLoaded", () => {
    const slots = document.querySelectorAll(".emoji-slot");
    const emojiBank = document.getElementById("emoji-bank");
    const resetBtn = document.getElementById("reset-btn");
    const feedback = document.getElementById("feedback");

    const allEmojis = ALL_EMOJIS;
    const selectedEmojis = allEmojis.sort(() => 0.5 - Math.random()).slice(0, 9);

    // Fill emoji bank with shuffled emojis
    selectedEmojis.forEach(emoji => {
        const span = document.createElement("span");
        span.className = "emoji";
        span.textContent = emoji;
        span.draggable = true;
        span.addEventListener("dragstart", (e) => {
            e.dataTransfer.setData("text", e.target.textContent);
        });
        emojiBank.appendChild(span);
    });

    // Drag and Drop Setup (emoji drag already handled inline)

    slots.forEach(slot => {
        slot.addEventListener("dragover", (e) => e.preventDefault());
        slot.addEventListener("drop", (e) => {
            e.preventDefault();
            const emoji = e.dataTransfer.getData("text");
            slot.textContent = emoji;
            saveSequence();
            checkPuzzle();
        });
    });

    // Auto-check puzzle when a drop occurs
    async function checkPuzzle() {
        const sequence = Array.from(slots).map(slot => slot.textContent || "");

        

        feedback.textContent = "⌛ Checking your solution...";

        try {
            const result = await checkWithOllama(sequence);
            feedback.innerHTML = result
                .split("\n")
                .map(line => `${line}`)
                .join("<br>");
        } catch (err) {
            feedback.textContent = "❌ Error while checking the puzzle.";
            console.error(err);
        }
    }

    // Reset Puzzle
    resetBtn.addEventListener("click", () => {
        slots.forEach(slot => slot.textContent = "");
        localStorage.removeItem("emojiSequence");
        feedback.textContent = "";
    });

    // Save sequence to localStorage
    function saveSequence() {
        const sequence = Array.from(slots).map(slot => slot.textContent || "");
        localStorage.setItem("emojiSequence", JSON.stringify(sequence));
    }
});

