<div id="booking-modal" class="modal hidden">
    <div class="modal-content modal-large">
        <div class="modal-header">
            <div class="header-text-container">
                <h2 id="modal-movie-title">Film Titel</h2>
                <div class="header-sub-info">
                    <p id="modal-info-text">Saal • Zeit</p>
                    <div id="tech-badges" class="tech-badges-container hidden">
                        <img src="/img/Dolby.png" alt="Dolby" class="tech-badge">
                        <img src="/img/dbox.jpg" alt="D-Box" class="tech-badge">
                    </div>
                </div>
            </div>
            <span class="close-btn">&times;</span>
        </div>

        <div class="screen-container">
            <div class="screen"></div>
            <p class="screen-text">LEINWAND</p>
        </div>

        <div class="booking-layout">
            <div class="seat-map-container">
                <div id="seat-grid" class="seat-grid-custom"></div>
            </div>
            <div id="booking-summary" class="summary-panel hidden">
                <h3>Deine Auswahl</h3>
                <div id="summary-items"></div>
                <div class="summary-total">
                    <div class="divider"></div>
                    <div class="total-row">
                        <span>Gesamtbetrag:</span>
                        <span id="total-price">0,00€</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="legend" id="dynamic-legend"></div>

        <button id="btn-confirm-seats" class="btn-primary" style="margin-top:20px">Plätze bestätigen</button>
    </div>
</div>

<script>
    import { seatLayouts, occupiedSeatsData, prices, cart, updateCart } from "../scripts/bigConstants";
    import type { MovieCartItem } from "../scripts/bigConstants";

    let currentBookingContext: any = null;
    let currentHallLayout: any = null;

    function getRowLabel(rowIndex: number) { return String(rowIndex + 1); }

    function buildHallLayout(hallName: string, baseConfig: any) {
        const rows = Number(baseConfig.rows || 0);
        const totalCols = Number(baseConfig.left || 0) + Number(baseConfig.right || 0);
        const isDeluxe = /deluxe/i.test(hallName);
        const left = isDeluxe ? Math.max(3, Number(baseConfig.left || 0) - 1) : Number(baseConfig.left || 0);
        const right = Math.max(0, totalCols - left);
        const vipRows = rows > 0 ? [rows] : [];
        const dboxMap = new Set();
        const markDboxRange = (row: number, start: number, width: number) => {
            for (let c = start; c < Math.min(totalCols, start + width); c++) dboxMap.add(`${row}-${c}`);
        };
        // ... (simplified logic) ...
        return { rows, left, right, totalCols, vipRows, dboxMap, isImax: Boolean(baseConfig.isImax) };
    }

    function updateBookingSummary() {
        const selectedSeats = Array.from(document.querySelectorAll("#seat-grid .seat.selected")) as HTMLElement[];
        const totalEl = document.getElementById("total-price");
        const summaryItems = document.getElementById("summary-items");
        let total = 0;
        if (summaryItems) {
            summaryItems.innerHTML = selectedSeats.map(seat => {
                const type = (seat.dataset.type || "normal") as keyof typeof prices;
                const p = prices[type] || prices.normal;
                total += p;
                return `<div class="summary-row"><span>${seat.dataset.seatId}</span><span>${p.toFixed(2).replace(".", ",")} EUR</span></div>`;
            }).join("");
        }
        if (totalEl) totalEl.innerText = `${total.toFixed(2).replace(".", ",")} EUR`;
        document.getElementById("booking-summary")?.classList.toggle("hidden", selectedSeats.length === 0);
    }

    function createSeats(hallName: string, time: any) {
        const seatGrid = document.getElementById("seat-grid");
        if (!seatGrid) return;
        seatGrid.innerHTML = "";
        const baseConfig = seatLayouts[hallName as keyof typeof seatLayouts];
        if (!baseConfig) return;
        currentHallLayout = buildHallLayout(hallName, baseConfig);
        const occupiedKey = `${hallName}-${time}`;
        const occupied = new Set(occupiedSeatsData[occupiedKey] || []);

        for (let r = 1; r <= currentHallLayout.rows; r++) {
            const row = document.createElement("div");
            row.className = "seat-row cinema-row";
            for (let c = 1; c <= currentHallLayout.totalCols; c++) {
                const seatId = `R${r}-P${c}`;
                const seat = document.createElement("button");
                seat.className = "seat " + (currentHallLayout.isImax ? "imax" : "normal");
                seat.dataset.seatId = seatId;
                if (occupied.has(seatId)) { seat.classList.add("occupied"); (seat as HTMLButtonElement).disabled = true; }
                else seat.addEventListener("click", () => { seat.classList.toggle("selected"); updateBookingSummary(); });
                row.appendChild(seat);
            }
            seatGrid.appendChild(row);
        }
    }

    (window as any).openBooking = (movie: string, hall: string, time: any) => {
        document.getElementById("modal-movie-title")!.innerText = movie;
        document.getElementById("modal-info-text")!.innerText = `${hall} • ${time} Uhr`;
        currentBookingContext = { movie, hall, time };
        createSeats(hall, time);
        document.getElementById("booking-modal")?.classList.remove("hidden");
    };

    document.getElementById("btn-confirm-seats")?.addEventListener("click", () => {
        const selected = Array.from(document.querySelectorAll("#seat-grid .seat.selected")) as HTMLElement[];
        if (!selected.length) return alert("Bitte wähle Plätze aus.");
        selected.forEach(seat => {
            const ticket: MovieCartItem = {
                id: Date.now() + Math.random(),
                category: "movie",
                title: currentBookingContext.movie,
                hall: currentBookingContext.hall,
                time: currentBookingContext.time,
                seatId: seat.dataset.seatId ?? "",
                price: prices[seat.dataset.type as keyof typeof prices] ?? prices.normal
            };
            cart.push(ticket);
        });
        updateCart(cart);
        window.dispatchEvent(new CustomEvent("cart-updated"));
        document.getElementById("booking-modal")?.classList.add("hidden");
        document.getElementById("snack-prompt-overlay")?.classList.remove("hidden");
    });
</script>

<script>
    const bookingModal = document.getElementById("booking-modal");
    const closeBtn = bookingModal?.querySelector(".close-btn");

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

    closeBtn?.addEventListener("click", closeBookingModal);

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

    document.addEventListener("keydown", (event) => {
        if (event.key === "Escape") closeBookingModal();
    });
</script>
