import { currentUser, loginUser, openAccountDashboard, registerUser } from "./account.js";
import { openBooking } from "./booking.js";
import { renderCart, saveCart, updateCartBadge } from "./cart.js";
import { renderCheckout } from "./checkout.js";
import type { MovieCatalog as MovieCatalogInterface } from "./interfaces.js";

export const movieCatalog: MovieCatalogInterface[] = [
    {    
        id: 1,
        title: "oh hell nah",
        genre: "n",
        duration: 3,
        fsk: "jfd",
        description: "jsss",
        poster: "g",
        backdrop: "f",
        rating: 1,
        year: "d",
    }
    ]

// Shared app state for legacy script files (account.js, booking.js, cart.js, checkout.js)
export const prices: Record<string, number> = { normal: 11.0, imax: 15.0, vip: 12.0, dbox: 16.0 };
export var seatLayouts = {
    "Kino 1": { rows: 6, left: 3, right: 7, vipRows: [5], dbox: [] },
    "Kino 2": { rows: 7, left: 5, right: 5, vipRows: [6], dbox: [] },
    "Deluxe 1": { rows: 10, left: 7, right: 8, vipRows: [9], dbox: [{ r: 4, c: 5, w: 4 }] },
    IMAX: { rows: 15, left: 10, right: 10, vipRows: [], dbox: [], isImax: true }
};
export var cart: any[] = JSON.parse(localStorage.getItem("eagleCart") || '[]');
export var occupiedSeatsData = JSON.parse(localStorage.getItem("eagleOccupied") || '{}');

document.addEventListener("DOMContentLoaded", () => {
    const views = {
        hero: document.querySelector(".hero"),
        moviesGrid: document.getElementById("movies-grid-section"),
        list: document.getElementById("movie-list-view"),
        halls: document.getElementById("halls-view"),
        dbox: document.getElementById("dbox-view"),
        collectors: document.getElementById("collectors-view"),
        about: document.getElementById("about-view"),
        snacks: document.getElementById("snacks-view"),
        cart: document.getElementById("cart-view"),
        checkout: document.getElementById("checkout-view"),
        account: document.getElementById("account-view")
    };

    const ui = {
        logo: document.getElementById("logo-home"),
        linkFilme: document.getElementById("link-filme"),
        linkSnacks: document.getElementById("link-snacks"),
        linkAbout: document.getElementById("link-about"),
        linkCart: document.getElementById("link-cart"),
        linkAccount: document.getElementById("link-account"),
        themeToggle: document.getElementById("theme-toggle"),
        heroBookingBtn: document.getElementById("hero-booking-btn"),
        heroSlider: document.getElementById("hero-slider"),
        heroDots: document.getElementById("hero-dots"),
        heroTitle: document.getElementById("hero-title"),
        heroText: document.getElementById("hero-text"),
        nowRunningRow: document.getElementById("now-running-row"),
        movieProgramList: document.getElementById("movie-program-list"),
        checkoutBtn: document.getElementById("btn-checkout-final"),
        backHomeBtn: document.getElementById("btn-back-home"),
        snacksView: document.getElementById("snacks-view"),
        snackOverlay: document.getElementById("snack-prompt-overlay"),
        btnYesSnacks: document.getElementById("btn-yes-snacks"),
        btnNoCart: document.getElementById("btn-no-cart"),
        bookingModal: document.getElementById("booking-modal"),
        closeBookingModalBtn: document.querySelector(".close-btn")
    };

    const checkoutSteps = {
        one: document.getElementById("checkout-step-1"),
        two: document.getElementById("checkout-step-2"),
        three: document.getElementById("checkout-step-3")
    };

    const hallRotation = ["IMAX", "Deluxe 1", "Kino 1", "Kino 2"];
    const timePatterns = [
        ["13:00", "15:20", "17:40", "20:00", "22:20"],
        ["13:00", "14:50", "17:10", "19:30", "21:50"],
        ["13:00", "15:10", "17:30", "19:50", "22:10"],
        ["13:00", "16:00", "18:20", "20:40"]
    ];

    let movieProgram: any = []; // TODO: Find type
    let heroItems: any = []; // TODO: find Type
    let heroIndex = 0;
    let heroTimer: any = null; // TODO: find type

    const weekdayShort = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];

    const hideAllViews = () => {
        Object.values(views).forEach((view) => view?.classList.add("hidden"));
        document.getElementById("about-tech-modal")?.classList.add("hidden");
        document.body.style.overflow = "auto";
    };

    const showHome = () => {
        hideAllViews();
        views.hero?.classList.remove("hidden");
        views.moviesGrid?.classList.remove("hidden");
        document.getElementById("about-tech-modal")?.classList.add("hidden");
        document.body.style.overflow = "auto";
        window.scrollTo({ top: 0, behavior: "smooth" });
    };

    const showMovieList = (programIndexToFocus: number = NaN) => {
        hideAllViews();
        views.list?.classList.remove("hidden");

        if (programIndexToFocus === null) {
            window.scrollTo({ top: 0, behavior: "smooth" });
            return;
        }

        const target = views.list?.querySelector(`[data-program-index="${programIndexToFocus}"]`);
        if (target) {
            target.scrollIntoView({ behavior: "smooth", block: "start" });
            target.classList.add("flash-focus");
            setTimeout(() => target.classList.remove("flash-focus"), 1200);
        }
    };

    const showStaticView = (viewElement: HTMLElement) => {
        if (!viewElement) {
            return;
        }

        hideAllViews();
        viewElement.classList.remove("hidden");
        window.scrollTo({ top: 0, behavior: "smooth" });
    };

    const showCheckoutStart = () => {
        if (!cart.length) {
            alert("Dein Warenkorb ist leer.");
            return;
        }

        hideAllViews();
        views.checkout?.classList.remove("hidden");
        checkoutSteps.one?.classList.remove("hidden");
        checkoutSteps.two?.classList.add("hidden");
        checkoutSteps.three?.classList.add("hidden");
        renderCheckout?.();
        window.scrollTo(0, 0);
    };

    const closeBookingModal = () => {
        ui.bookingModal?.classList.add("hidden");
    };

    const escapeHtml = (value: string) => String(value || "")
        .replaceAll("&", "&amp;")
        .replaceAll("<", "&lt;")
        .replaceAll(">", "&gt;")
        .replaceAll('"', "&quot;")
        .replaceAll("'", "&#39;");

    const formatDateShort = (dateObj: any) => {
        const day = String(dateObj.getDate()).padStart(2, "0");
        const month = String(dateObj.getMonth() + 1).padStart(2, "0");
        return `${day}.${month}.`;
    };

    const buildDayMeta = (offset: number) => {
        const date = new Date();
        date.setHours(0, 0, 0, 0);
        date.setDate(date.getDate() + offset);

        const weekday = weekdayShort[date.getDay()];
        const formattedDate = formatDateShort(date);

        if (offset === 0) {
            return {
                offset,
                date,
                short: "Heute",
                long: `Heute, ${formattedDate}`
            };
        }

        if (offset === 1) {
            return {
                offset,
                date,
                short: "Morgen",
                long: `Morgen, ${formattedDate}`
            };
        }

        return {
            offset,
            date,
            short: weekday,
            long: `${weekday}, ${formattedDate}`
        };
    };

    const buildScheduleForMovie = (movieIndex: number) => {
        return Array.from({ length: 7 }, (_, dayOffset) => {
            const dayMeta = buildDayMeta(dayOffset);
            const pattern = timePatterns[(movieIndex + dayOffset) % timePatterns.length] || "Error reading";
            const desiredCount = 4 + ((movieIndex + dayOffset) % 2);
            const showCount = Math.min(pattern.length, desiredCount);

            //@ts-ignore
            const showings = pattern.slice(0, showCount).map((time: any, slotIndex: number) => { // TODO: fix map issue
                const hall = hallRotation[(movieIndex + dayOffset + slotIndex) % hallRotation.length];
                return { time, hall };
            });

            return {
                ...dayMeta,
                showings
            };
        });
    };

    const buildMovieProgram = () => {
        movieProgram = movieCatalog.map((movie: any, movieIndex: number) => ({
            ...movie,
            schedule: buildScheduleForMovie(movieIndex)
        }));
        heroItems = movieProgram.slice(0, 5);
    };

    const setHeroSlide = (index: number) => {
        if (!heroItems.length || !ui.heroSlider) {
            return;
        }

        heroIndex = (index + heroItems.length) % heroItems.length;

        ui.heroSlider.querySelectorAll(".hero-slide").forEach((slide, slideIndex) => {
            slide.classList.toggle("active", slideIndex === heroIndex);
        });

        ui.heroDots?.querySelectorAll(".hero-dot").forEach((dot, dotIndex) => {
            dot.classList.toggle("active", dotIndex === heroIndex);
        });

        const activeMovie = heroItems[heroIndex];
        if (ui.heroTitle) {
            ui.heroTitle.textContent = activeMovie.title;
        }
        if (ui.heroText) {
            ui.heroText.textContent = `${activeMovie.genre} • ${activeMovie.duration} Min. • Heute erste Vorstellung um 13:00 Uhr.`;
        }
    };

    const renderHero = () => {
        if (!ui.heroSlider || !heroItems.length) {
            return;
        }

        ui.heroSlider.innerHTML = heroItems.map((movie: any, index: number) => `
            <div class="hero-slide ${index === 0 ? "active" : ""}" style="background-image: linear-gradient(118deg, rgba(0,0,0,0.34), rgba(0,0,0,0.04)), url('${escapeHtml(movie.backdrop || movie.poster)}');"></div>
        `).join("");

        if (ui.heroDots) {
            ui.heroDots.innerHTML = heroItems.map((_: any, index: number) => `
                <button type="button" class="hero-dot ${index === 0 ? "active" : ""}" data-hero-index="${index}"></button>
            `).join("");

            ui.heroDots.addEventListener("click", (event: any) => {
                const dotTarget = event.target || 0;
                const dot = dotTarget.closest(".hero-dot");
                if (!dot) {
                    return;
                }

                const nextIndex = Number(dot.dataset.heroIndex || 0);
                setHeroSlide(nextIndex);

                if (heroTimer) {
                    clearInterval(heroTimer);
                    heroTimer = setInterval(() => setHeroSlide(heroIndex + 1), 6500);
                }
            });
        }

        setHeroSlide(0);

        if (heroTimer) {
            clearInterval(heroTimer);
        }

        heroTimer = setInterval(() => {
            setHeroSlide(heroIndex + 1);
        }, 6500);
    };

    const renderNowRunningRow = () => {
        if (!ui.nowRunningRow) {
            return;
        }

        // TODO: implement movie interface
        ui.nowRunningRow.innerHTML = movieProgram.map((movie: any, index: number) => /*html*/` 
            <article class="running-poster">
                <img src="${escapeHtml(movie.poster)}" alt="${escapeHtml(movie.title)}">
                <div class="running-meta">
                    <h4>${escapeHtml(movie.title)}</h4>
                    <p>${escapeHtml(movie.genre)}</p>
                    <button type="button" class="open-program-btn" data-program-index="${index}">Spielzeiten ansehen</button>
                </div>
            </article>
        `).join("");
    };

    const renderScheduleRows = (programIndex: number, dayIndex: number) => {
        const movie = movieProgram[programIndex];
        if (!movie) {
            return;
        }

        const day = movie.schedule[dayIndex];
        const body = document.getElementById(`schedule-body-${programIndex}`);
        if (!body || !day) {
            return;
        }

        body.innerHTML = day.showings.map((showing: { hall: string; time: string; }) => /*html*/`
            <button class="schedule-row time-chip program-time-row" data-movie="${escapeHtml(movie.title)}" data-hall="${escapeHtml(showing.hall)}" data-time="${escapeHtml(showing.time)}">
                <span>${escapeHtml(day.long)}</span>
                <span class="hall-pill">${escapeHtml(showing.hall)}</span>
                <span class="time-btn">${escapeHtml(showing.time)}</span>
            </button>
        `).join("");
    };

    const renderMovieProgramList = () => {
        if (!ui.movieProgramList) {
            return;
        }

        ui.movieProgramList.innerHTML = movieProgram.map((movie: { schedule: any[]; poster: string; title: string; fsk: string; duration: any; genre: string; description: string; }, programIndex: any) => {
            const dayTabs = movie.schedule.map((day, dayIndex) => /*html*/`
                <button type="button" class="program-day-tab ${dayIndex === 0 ? "active" : ""}" data-program-index="${programIndex}" data-day-index="${dayIndex}">
                    <span>${escapeHtml(day.short)}</span>
                    <small>${escapeHtml(formatDateShort(day.date))}</small>
                </button>
            `).join("");

            return /*html*/`
                <article class="detailed-card program-card reveal-on-scroll" data-program-index="${programIndex}">
                    <div class="card-left">
                        <img src="${escapeHtml(movie.poster)}" alt="${escapeHtml(movie.title)}">
                        <span class="fsk fsk-${escapeHtml(movie.fsk)}">${escapeHtml(movie.fsk)}</span>
                    </div>
                    <div class="card-right">
                        <div class="card-header">
                            <h2>${escapeHtml(movie.title)}</h2>
                            <span class="duration">${movie.duration} Min. | ${escapeHtml(movie.genre)} | FSK: ${escapeHtml(movie.fsk)}</span>
                        </div>
                        <p class="description">${escapeHtml(movie.description)}</p>

                        <div class="program-day-tabs">${dayTabs}</div>

                        <div class="schedule-container program-schedule-shell">
                            <div class="schedule-header">
                                <span>Tag</span><span>Kinosaal</span><span>Uhrzeit</span>
                            </div>
                            <div id="schedule-body-${programIndex}" class="program-schedule-body"></div>
                        </div>
                    </div>
                </article>
            `;
        }).join("");

        movieProgram.forEach((_: any, programIndex: number) => {
            renderScheduleRows(programIndex, 0);
        });
    };

    const initRevealAnimations = () => {
        const revealElements = Array.from(document.querySelectorAll(".reveal-on-scroll"));
        if (!revealElements.length) {
            return;
        }

        if (!("IntersectionObserver" in window)) {
            revealElements.forEach((element) => element.classList.add("is-visible"));
            return;
        }

        const observer = new IntersectionObserver((entries, obs) => {
            entries.forEach((entry) => {
                if (!entry.isIntersecting) {
                    return;
                }

                entry.target.classList.add("is-visible");
                obs.unobserve(entry.target);
            });
        }, { threshold: 0.2 });

        revealElements.forEach((element) => observer.observe(element));
    };

    const renderMovieExperience = () => {
        buildMovieProgram();
        renderHero();
        renderNowRunningRow();
        renderMovieProgramList();
        initRevealAnimations();
    };

    const bindNavigation = () => {
        ui.logo?.addEventListener("click", showHome);

        ui.linkFilme?.addEventListener("click", (event) => {
            event.preventDefault();
            showMovieList();
        });

        ui.linkSnacks?.addEventListener("click", (event) => {
            event.preventDefault();
            if (views.snacks) {
                showStaticView(views.snacks);
            }
        });

        ui.linkAbout?.addEventListener("click", (event) => {
            event.preventDefault();
            if (views.about) {
                showStaticView(views.about);
            }
        });

        ui.linkCart?.addEventListener("click", (event) => {
            event.preventDefault();
            hideAllViews();
            views.cart?.classList.remove("hidden");
            renderCart?.();
        });

        ui.linkAccount?.addEventListener("click", (event) => {
            event.preventDefault();
            hideAllViews();
            views.account?.classList.remove("hidden");

            const isUserLoggedIn = typeof currentUser !== "undefined" && currentUser;
            if (isUserLoggedIn && typeof openAccountDashboard === "function") {
                openAccountDashboard();
            }
        });

        ui.heroBookingBtn?.addEventListener("click", () => {
            showMovieList();
        });

        ui.checkoutBtn?.addEventListener("click", showCheckoutStart);
        ui.backHomeBtn?.addEventListener("click", showHome);
    };

    const bindProgramActions = () => {
        views.moviesGrid?.addEventListener("click", (event: any) => {
            const trigger = event.target.closest(".open-program-btn");
            if (!trigger) {
                return;
            }

            const programIndex = Number(trigger.dataset.programIndex) || 0;
            showMovieList(programIndex);
        });

        ui.movieProgramList?.addEventListener("click", (event: any) => {
            const dayButton = event.target.closest(".program-day-tab");
            if (!dayButton) {
                return;
            }

            const programIndex = Number(dayButton.dataset.programIndex || 0);
            const dayIndex = Number(dayButton.dataset.dayIndex || 0);

            const tabRow = dayButton.closest(".program-day-tabs");
            tabRow?.querySelectorAll(".program-day-tab").forEach((tab: { classList: { remove: (arg0: string) => any; }; }) => tab.classList.remove("active"));
            dayButton.classList.add("active");

            renderScheduleRows(programIndex, dayIndex);
        });
    };

    const bindHomeInfoNavigation = () => {
        const openButtons = Array.from(document.querySelectorAll("[data-home-view-open]"));
        const backButtons = Array.from(document.querySelectorAll("[data-go-home]"));
        const aboutOpenButtons = Array.from(document.querySelectorAll("[data-about-modal-open]"));
        const aboutCloseButtons = Array.from(document.querySelectorAll("[data-about-modal-close]"));
        const aboutModal = document.getElementById("about-tech-modal");

        if (!openButtons.length) {
            return;
        }

        const targetMap = {
            "halls-view": views.halls,
            "dbox-view": views.dbox,
            "collectors-view": views.collectors
        };

        openButtons.forEach((button) => {
            button.addEventListener("click", () => {
                const targetId = button.getAttribute("data-home-view-open") as keyof typeof targetMap;
                const target = targetId ? targetMap[targetId] : null;
                if (target) {
                    showStaticView(target);
                }
            });
        });

        backButtons.forEach((button) => {
            button.addEventListener("click", () => {
                showHome();
            });
        });

        aboutOpenButtons.forEach((button) => {
            button.addEventListener("click", () => {
                const targetId = button.getAttribute("data-about-modal-open");
                if (targetId === "about-tech-modal" && aboutModal) {
                    aboutModal.classList.remove("hidden");
                    document.body.style.overflow = "hidden";
                }
            });
        });

        aboutCloseButtons.forEach((button) => {
            button.addEventListener("click", () => {
                aboutModal?.classList.add("hidden");
                document.body.style.overflow = "auto";
            });
        });

        aboutModal?.addEventListener("click", (event) => {
            if (event.target === aboutModal) {
                aboutModal.classList.add("hidden");
                document.body.style.overflow = "auto";
            }
        });

        document.addEventListener("keydown", (event) => {
            if (event.key === "Escape" && aboutModal && !aboutModal.classList.contains("hidden")) {
                aboutModal.classList.add("hidden");
                document.body.style.overflow = "auto";
            }
        });
    };

    const initThemeToggle = () => {
        if (!ui.themeToggle) {
            return;
        }

        const THEME_KEY = "eagleTheme";

        const applyTheme = (theme: any) => {
            const isLight = theme === "light";
            document.body.classList.toggle("theme-light", isLight);
            document.body.classList.toggle("theme-dark", !isLight);
            //@ts-ignore
            ui.themeToggle.classList.toggle("is-light", isLight);
            localStorage.setItem(THEME_KEY, isLight ? "light" : "dark");
        };

        const storedTheme = localStorage.getItem(THEME_KEY);
        applyTheme(storedTheme === "light" ? "light" : "dark");

        ui.themeToggle.addEventListener("click", () => {
            const nextTheme = document.body.classList.contains("theme-light") ? "dark" : "light";
            applyTheme(nextTheme);
        });
    };

    const bindAccountActions = () => {
        const registerModal = document.getElementById("register-modal");
        const forgotModal = document.getElementById("forgot-modal");
        const forgotEmailInput = document.getElementById("forgot-email") as HTMLInputElement;
        const resetMessage = document.getElementById("reset-message");
        const loginError = document.getElementById("login-error");
        const loginEmailInput = document.getElementById("login-email");
        const loginPasswordInput = document.getElementById("login-password");

        const openModal = (modal: HTMLElement | null) => modal?.classList.remove("hidden");
        const closeModal = (modal: HTMLElement | null) => modal?.classList.add("hidden");
        const triggerLogin = () => {
            loginError?.classList.add("hidden");
            if (typeof loginUser === "function") {
                loginUser();
            }
        };

        document.getElementById("btn-open-register")?.addEventListener("click", () => {
            openModal(registerModal);
        });

        document.getElementById("btn-close-register")?.addEventListener("click", () => {
            closeModal(registerModal);
        });

        document.getElementById("btn-register-save")?.addEventListener("click", () => {
            if (typeof registerUser === "function") {
                registerUser();
            }
        });

        document.getElementById("btn-login-account")?.addEventListener("click", triggerLogin);

        [loginEmailInput, loginPasswordInput].forEach((input) => {
            input?.addEventListener("keydown", (event) => {
                if (event.key !== "Enter") {
                    return;
                }

                event.preventDefault();
                triggerLogin();
            });
        });

        document.getElementById("btn-forgot-password")?.addEventListener("click", () => {
            if (forgotEmailInput != null) {
                forgotEmailInput.value = "";
            }
            resetMessage?.classList.add("hidden");
            openModal(forgotModal);
        });

        document.getElementById("btn-close-forgot")?.addEventListener("click", () => {
            closeModal(forgotModal);
        });

        document.getElementById("btn-send-reset")?.addEventListener("click", () => {
            const email = forgotEmailInput?.value.trim() || "";
            if (!email || !email.includes("@")) {
                alert("Bitte gib eine gueltige E-Mail-Adresse ein.");
                return;
            }

            if (resetMessage) {
                resetMessage.textContent = "Wenn ein Konto existiert, wurde ein Reset-Code simuliert versendet.";
                resetMessage.classList.remove("hidden");
            }
        });

        registerModal?.addEventListener("click", (event) => {
            if (event.target === registerModal) {
                closeModal(registerModal);
            }
        });

        forgotModal?.addEventListener("click", (event) => {
            if (event.target === forgotModal) {
                closeModal(forgotModal);
            }
        });

        document.addEventListener("keydown", (event) => {
            if (event.key === "Escape") {
                closeModal(registerModal);
                closeModal(forgotModal);
            }
        });
    };

    const bindGlobalDocumentClicks = () => {
        document.addEventListener("click", (event: any) => {
            if (event.target.classList.contains("opt-btn")) {
                const optionGroup = event.target.parentElement;
                optionGroup?.querySelectorAll(".opt-btn").forEach((button: { classList: { remove: (arg0: string) => any; }; }) => button.classList.remove("active"));
                event.target.classList.add("active");
            }

            const deleteBtn = event.target.closest(".btn-delete-item");
            if (deleteBtn?.dataset.key) {
                const row = deleteBtn.closest(".cart-item-row");
                if (row) {
                    row.classList.add("slide-out-left");
                    row.querySelectorAll("button").forEach((button: { disabled: boolean; }) => {
                        button.disabled = true;
                    });

                    setTimeout(() => {
                        //@ts-ignore
                        removeFromCartByKey(deleteBtn.dataset.key); //TODO: removeFromCartByKey doesnt exist
                    }, 380);
                } else {
                    //@ts-ignore
                    removeFromCartByKey(deleteBtn.dataset.key); //TODO: removeFromCartByKey doesnt exist
                }
                return;
            }

            const chip = event.target.closest(".time-chip");
            if (chip) {
                const movieFromData = chip.getAttribute("data-movie");
                const movieCard = chip.closest(".movie-card, .detailed-card, .program-card");
                const movie = movieFromData || movieCard?.querySelector("h2, h3")?.innerText || "Film";
                const hall = chip.getAttribute("data-hall");
                const time = chip.getAttribute("data-time");

                if (hall && time && typeof openBooking === "function") {
                    openBooking(movie, hall, time);
                }
            }

            const qtyBtn = event.target.closest(".btn-qty");
            if (!qtyBtn) {
                return;
            }

            const action = qtyBtn.dataset.action;
            const key = qtyBtn.dataset.key;
            if (!action || !key) {
                return;
            }

            const relatedItem = cart.find((item: { category: string; seatId: any; hall: any; time: any; title: any; }) => {
                const infoText = item.category === "movie"
                    ? `Sitz: ${item.seatId} (${item.hall})`
                    : item.time;
                return `${item.title}-${item.hall}-${infoText}` === key;
            });

            if (!relatedItem || relatedItem.category === "movie") {
                return;
            }

            if (action === "plus") {
                cart.push({ ...relatedItem, id: Date.now() + Math.random() });
            } else {
                const keyList = cart.map((item: { category: string; seatId: any; hall: any; time: any; title: any; }) => {
                    const infoText = item.category === "movie"
                        ? `Sitz: ${item.seatId} (${item.hall})`
                        : item.time;
                    return `${item.title}-${item.hall}-${infoText}`;
                });
                const lastMatch = keyList.lastIndexOf(key);

                if (lastMatch !== -1) {
                    cart.splice(lastMatch, 1);
                }
            }

            saveCart?.();
            renderCart?.();
        });
    };

    const bindSnacksActions = () => {
        ui.snacksView?.addEventListener("click", (event: any) => {
            const sizeChip = event.target.closest(".size-chip");
            if (!sizeChip) {
                return;
            }

            const snackCard = sizeChip.closest(".snack-card");
            if (!snackCard) {
                return;
            }

            const snackTitle = snackCard.querySelector("h3, h2")?.innerText || "Snack";
            const snackImg = snackCard.querySelector("img")?.src || "";
            const priceSpan = sizeChip.querySelector("span");
            const rawPriceText = (priceSpan ? priceSpan.innerText : sizeChip.innerText)
                .replace("EUR", "")
                .replace("€", "")
                .replace(",", ".")
                .trim();
            const priceVal = parseFloat(rawPriceText) || 0;
            const sizeVal = sizeChip.innerText.replace(priceSpan?.innerText || "", "").trim() || "Standard";
            const activeOption = snackCard.querySelector(".opt-btn.active");
            const variantVal = activeOption ? activeOption.innerText : "Normal";

            cart.push({
                id: Date.now() + Math.random(),
                category: "snack",
                title: snackTitle,
                hall: sizeVal,
                time: variantVal,
                type: "SNACK",
                price: priceVal,
                img: snackImg
            });

            saveCart?.();

            const originalHtml = sizeChip.innerHTML;
            sizeChip.innerHTML = "Hinzugefügt!";
            setTimeout(() => {
                sizeChip.innerHTML = originalHtml;
            }, 800);
        });

        document.querySelectorAll(".tab-btn").forEach((button: any) => {
            button.addEventListener("click", () => {
                document.querySelectorAll(".tab-btn").forEach((tab) => tab.classList.remove("active"));
                button.classList.add("active");

                document.querySelectorAll(".snack-category").forEach((category) => category.classList.add("hidden"));
                document.getElementById(button.dataset.target)?.classList.remove("hidden");
            });
        });
    };

    const bindOverlayActions = () => {
        ui.btnYesSnacks?.addEventListener("click", () => {
            ui.snackOverlay?.classList.add("hidden");
            hideAllViews();
            views.snacks?.classList.remove("hidden");
            document.body.style.overflow = "auto";
        });

        ui.btnNoCart?.addEventListener("click", () => {
            ui.snackOverlay?.classList.add("hidden");
            hideAllViews();
            views.cart?.classList.remove("hidden");
            renderCart?.();
            document.body.style.overflow = "auto";
        });
    };

    const bindBookingModalClose = () => {
        ui.closeBookingModalBtn?.addEventListener("click", closeBookingModal);

        ui.bookingModal?.addEventListener("click", (event) => {
            if (event.target === ui.bookingModal) {
                closeBookingModal();
            }
        });
    };
    // @ts-ignore
    window.removeFromCartByKey = function removeFromCartByKey(key: string) {
        cart = cart.filter((item: { category: string; seatId: any; hall: any; time: any; title: any; }) => {
            const infoText = item.category === "movie"
                ? `Sitz: ${item.seatId} (${item.hall})`
                : item.time;
            return `${item.title}-${item.hall}-${infoText}` !== key;
        });

        saveCart?.();
        renderCart?.();
    };

    renderMovieExperience();
    initThemeToggle();
    bindNavigation();
    bindProgramActions();
    bindHomeInfoNavigation();
    bindAccountActions();
    bindGlobalDocumentClicks();
    bindSnacksActions();
    bindOverlayActions();
    bindBookingModalClose();

    updateCartBadge?.();
    renderCheckout?.();
});

export function emptyCart() {
    cart = []
    return
}