<section id="cart-view" class="cart-section">
    <div class="container" style="padding: 120px 8% 50px 8%;">
        <h1 class="list-title">Dein Warenkorb</h1>

        <div class="cart-container">
            <div class="cart-left">
                <div id="cart-items-list"></div>
            </div>

            <div class="cart-right">
                <div class="summary-box-black">
                    <h2>Zusammenfassung</h2>
                    <div class="summary-row-large">
                        <span>Gesamtsumme:</span>
                        <span id="cart-total-right">0,00€</span>
                    </div>
                    <p id="cart-vat-right" style="text-align:right; color:#86868b; font-size:0.8rem; margin-top:5px;">
                        inkl. 19% MwSt: 0,00€
                    </p>

                    <button id="btn-checkout-final" class="blue-button">Jetzt kostenpflichtig bestellen</button>

                    <div class="payment-methods" style="margin-top: 25px; text-align: center;">
                        <p style="font-size: 0.75rem; color: #86868b; margin-bottom: 12px;">Sicher bezahlen mit</p>
                        <div style="display: flex; justify-content: center; gap: 15px; opacity: 0.6;">
                            <img src="/img/paypal.png" alt="PayPal" style="height: 20px;">
                            <img src="/img/visa.png" alt="Visa" style="height: 20px;">
                            <img src="/img/mastercard.png" alt="Mastercard" style="height: 20px;">
                            <img src="/img/applepay.png" alt="Apple Pay" style="height: 20px;">
                            <img src="/img/googlepay.png" alt="Google Pay" style="height: 20px;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    import { cart, updateCart } from "../scripts/bigConstants";

    function formatEuro(value: number) {
        return `${Number(value || 0).toFixed(2).replace(".", ",")} EUR`;
    }

    function escapeHtml(value: any) {
        return String(value || "")
            .replaceAll("&", "&amp;")
            .replaceAll("<", "&lt;")
            .replaceAll(">", "&gt;")
            .replaceAll('"', "&quot;")
            .replaceAll("'", "&#39;");
    }

    function buildCartKey(item: any) {
        const infoText = item.category === "movie"
            ? `Sitz: ${item.seatId} (${item.hall})`
            : item.time;
        return `${item.title}-${item.hall}-${infoText}`;
    }

    function isDrinkItem(item: any) {
        if (item.category !== "snack") return false;
        const title = String(item.title || "").toLowerCase();
        const size = String(item.hall || "").toLowerCase();
        const drinkKeywords = ["cola", "sprite", "fanta", "mezzo", "fuze", "wasser", "getraenk", "drink"];
        return drinkKeywords.some((word) => title.includes(word)) || size.includes("l");
    }

    function buildItemInfo(item: any) {
        if (item.category === "movie") {
            return `
                <div>Sitzplatz: ${escapeHtml(item.seatId || "-")}</div>
                <div>Saal: ${escapeHtml(item.hall || "-")}</div>
                <div>Uhrzeit: ${escapeHtml(item.time || "-")} Uhr</div>
            `;
        }
        if (isDrinkItem(item)) {
            return `
                <div>Variante: ${escapeHtml(item.time || "-")}</div>
                <div>Groesse: ${escapeHtml(item.hall || "-")}</div>
            `;
        }
        return `
            <div>Kategorie: Snack</div>
            <div>Variante: ${escapeHtml(item.time || "-")}</div>
            <div>Groesse: ${escapeHtml(item.hall || "-")}</div>
        `;
    }

    function groupCartItems() {
        const groups = new Map();
        cart.forEach((item: any) => {
            const key = buildCartKey(item);
            if (!groups.has(key)) {
                groups.set(key, { key, quantity: 0, total: 0, item });
            }
            const group = groups.get(key);
            group.quantity += 1;
            group.total += Number(item.price || 0);
        });
        return Array.from(groups.values());
    }

    export function renderCart() {
        const cartList = document.getElementById("cart-items-list");
        const totalEl = document.getElementById("cart-total-right");
        const vatEl = document.getElementById("cart-vat-right");

        if (!cartList || !totalEl || !vatEl) return;

        if (!Array.isArray(cart) || cart.length === 0) {
            cartList.innerHTML = '<p>Dein Warenkorb ist leer.</p>';
            totalEl.innerText = formatEuro(0);
            vatEl.innerText = `inkl. 19% MwSt: ${formatEuro(0)}`;
            return;
        }

        const groupedItems = groupCartItems();
        const header = `
            <div class="cart-header-row">
                <div class="col-amount">MENGE</div>
                <div class="col-img">VORSCHAU</div>
                <div class="col-product">NAME</div>
                <div class="col-details">INFO</div>
                <div class="col-price">PREIS</div>
                <div class="col-action">AKTION</div>
            </div>
        `;

        const rows = groupedItems.map((group) => {
            const imageHtml = group.item.img
                ? `<img class="cart-img-small" src="${escapeHtml(group.item.img)}" alt="${escapeHtml(group.item.title)}">`
                : `<div class="cart-img-fallback">Kein Bild</div>`;
            const quantityHtml = group.item.category === "movie"
                ? `<div class="qty-static" aria-label="Feste Ticketanzahl">${group.quantity}x</div>`
                : `
                    <div class="qty-stepper">
                        <button class="btn-qty" data-action="minus" data-key="${escapeHtml(group.key)}">-</button>
                        <span>${group.quantity}</span>
                        <button class="btn-qty" data-action="plus" data-key="${escapeHtml(group.key)}">+</button>
                    </div>
                `;

            return `
                <div class="cart-item-row">
                    <div class="col-amount">${quantityHtml}</div>
                    <div class="col-img">${imageHtml}</div>
                    <div class="col-product">${escapeHtml(group.item.title)}</div>
                    <div class="col-details cart-item-info">${buildItemInfo(group.item)}</div>
                    <div class="col-price">${formatEuro(group.total)}</div>
                    <div class="col-action">
                        <button class="btn-delete-item" data-key="${escapeHtml(group.key)}" aria-label="Eintrag entfernen"><span aria-hidden="true">🗑️</span></button>
                    </div>
                </div>
            `;
        }).join("");

        cartList.innerHTML = header + rows;

        const total = cart.reduce((sum, item) => sum + Number(item.price || 0), 0);
        const vat = total - total / 1.19;
        totalEl.innerText = formatEuro(total);
        vatEl.innerText = `inkl. 19% MwSt: ${formatEuro(vat)}`;
    }

    window.addEventListener("cart-updated", renderCart);
    renderCart();

    document.getElementById("cart-view")?.addEventListener("click", (event: any) => {
        const deleteBtn = event.target.closest(".btn-delete-item");
        if (deleteBtn) {
            const key = deleteBtn.dataset.key;
            const newCart = cart.filter(item => buildCartKey(item) !== key);
            updateCart(newCart);
            window.dispatchEvent(new CustomEvent("cart-updated"));
            return;
        }

        const qtyBtn = event.target.closest(".btn-qty");
        if (qtyBtn) {
            const action = qtyBtn.dataset.action;
            const key = qtyBtn.dataset.key;
            if (action === "plus") {
                const item = cart.find(i => buildCartKey(i) === key);
                if (item) cart.push({...item, id: Date.now() + Math.random()});
            } else {
                const idx = cart.findIndex(i => buildCartKey(i) === key);
                if (idx !== -1) cart.splice(idx, 1);
            }
            updateCart(cart);
            window.dispatchEvent(new CustomEvent("cart-updated"));
        }
    });

    document.getElementById("btn-checkout-final")?.addEventListener("click", () => {
        if (!cart.length) {
            alert("Dein Warenkorb ist leer.");
            return;
        }
        window.location.href = "/checkout";
    });
</script>
